谢谢杰夫,这使我走上了正确的道路。DefaultModelBinder足够聪明,可以为我做所有的魔术…我的问题出在我的Widget类型中。匆忙中,我的类型定义为:
public class Widget{ public int Id; public string Name; public decimal Price;}请注意,该类型具有公共字段而不是公共属性。一旦将其更改为属性,它就会起作用。这是可以正常工作的最终源代码:
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:
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; } }}


