Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <pre><code>public class Widget { public int Id; public string Name; public decimal Price; } </code></pre> <p>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:</p> <p>Widget.aspx:</p> <pre><code>&lt;%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Widget.aspx.cs" Inherits="MvcAjaxApp2.Views.Home.Widget" %&gt; &lt;asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"&gt; &lt;script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function SaveWidget() { var formData = $("#Form1").serializeArray(); $.post("/Home/SaveWidget", formData, function(data){ alert(data.Result); }, "json"); } &lt;/script&gt; &lt;form id="Form1"&gt; &lt;input type="hidden" name="widget.Id" value="1" /&gt; &lt;input type="text" name="widget.Name" value="my widget" /&gt; &lt;input type="text" name="widget.Price" value="5.43" /&gt; &lt;input type="button" value="Save" onclick="SaveWidget()" /&gt; &lt;/form&gt; &lt;/asp:Content&gt; </code></pre> <p>HomeController.cs:</p> <pre><code>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; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload