如何使用JSON复杂类型传递到ASP.NET MVC控制器 [英] How to pass complex type using json to ASP.NET MVC controller

查看:175
本文介绍了如何使用JSON复杂类型传递到ASP.NET MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个观点,即允许用户为新的Widget输入/编辑数据。我想这些数据形成了成JSON对象,并通过AJAX发送到我的控制器,所以我可以做服务器上验证没有回发。

I have a View that allows a user to enter/edit data for a new Widget. I'd like to form up that data into a json object and send it to my controller via AJAX so I can do the validation on the server without a postback.

我知道了所有的工作,但我无法弄清楚如何通过数据,所以我的控制器方法可以接受一个复杂的小部件类型,而不是为每个属性单独的参数。

I've got it all working, except I can't figure out how to pass the data so my controller method can accept a complex Widget type instead of individual parameters for each property.

所以,如果这是我的目标:

So, if this is my object:

public class Widget
{
   public int Id { get; set; }
   public string Name { get; set; }
   public decimal Price { get; set; }
}

我想我的控制器方法如下所示:

I'd like my controller method to look something like this:

public JsonResult Save(Widget widget)
{
   ...
}

目前,我的jQuery是这样的:

Currently, my jQuery looks like this:

var formData = $("#Form1").serializeArray();

$.post("/Widget/Save",
   formData,
   function(result){}, "json");

我的窗体(Form)有对小工具(ID,名称,价格),每个属性的输入字段。这个伟大的工程,但它最终通过了Widget的每个属性作为单独的参数来我控制器的方法。

My form (Form1) has an input field for each property on the Widget (Id, Name, Price). This works great, but it ultimately passes each property of the Widget as a separate parameter to my controller method.

有,我可以拦截的数据,也许用一个ActionFilterAttribute方式,并反序列化到一个Widget对象我的控制器方法被调用之前?

Is there a way I could "intercept" the data, maybe using an ActionFilterAttribute, and deserialize it to a Widget object before my controller method gets called?

推荐答案

感谢杰夫,这让我在正确的道路上。该DefaultModelBinder是足够聪明,做所有的魔法我...我的问题是在我的窗口小部件的类型。在我的匆忙,我喜欢的类型被定义为:

Thanks Jeff, that got me on the right path. The DefaultModelBinder is smart enough to do all the magic for me...my problem was in my Widget type. In my haste, my type was defined as:

public class Widget
{
   public int Id;
   public string Name;
   public decimal Price;
}

注意该类型具有公共领域而不是公共属性。有一次,我改变了那些特性,它的工作。这里的最后一个来源$ C ​​$ C,它正常工作:

Notice that the type has public fields instead of public properties. Once I changed those to properties, it worked. Here's the final source code that works correctly:

Widget.aspx:

Widget.aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Widget.aspx.cs" Inherits="MvcAjaxApp2.Views.Home.Widget" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>   
    <script type="text/javascript"> 
    function SaveWidget()
    {
        var formData = $("#Form1").serializeArray();

        $.post("/Home/SaveWidget",
        formData,
        function(data){
            alert(data.Result);
        }, "json");
    }
    </script>
    <form id="Form1">
        <input type="hidden" name="widget.Id" value="1" />
        <input type="text" name="widget.Name" value="my widget" />
        <input type="text" name="widget.Price" value="5.43" />
        <input type="button" value="Save" onclick="SaveWidget()" />
    </form>
</asp:Content>

HomeController.cs:

HomeController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcAjaxApp2.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
    	public ActionResult Index()
    	{
    		ViewData["Title"] = "Home Page";
    		ViewData["Message"] = "Welcome to ASP.NET MVC!";
    		return View();
    	}

    	public ActionResult About()
    	{
    		ViewData["Title"] = "About Page";
    		return View();
    	}

    	public ActionResult Widget()
    	{
    		ViewData["Title"] = "Widget";
    		return View();
    	}

    	public JsonResult SaveWidget(Widget widget)
    	{
    		// Save the Widget
    		return Json(new { Result = String.Format("Saved widget: '{0}' for ${1}", widget.Name, widget.Price) });
    	}
    }
    public class Widget
    {
    	public int Id { get; set; }
    	public string Name { get; set; }
    	public decimal Price { get; set; }
    }
}

这篇关于如何使用JSON复杂类型传递到ASP.NET MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆