Asp.net
如何使用 json 將復雜類型傳遞給 ASP.NET MVC 控制器
我有一個視圖,允許使用者輸入/編輯新小元件的數據。我想將該數據形成一個 json 對象並通過 AJAX 將其發送到我的控制器,這樣我就可以在伺服器上進行驗證而無需回發。
我已經完成了所有工作,只是我不知道如何傳遞數據,因此我的控制器方法可以接受複雜的 Widget 類型,而不是每個屬性的單獨參數。
所以,如果這是我的對象:
public class Widget { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }我希望我的控制器方法看起來像這樣:
public JsonResult Save(Widget widget) { ... }目前,我的 jQuery 看起來像這樣:
var formData = $("#Form1").serializeArray(); $.post("/Widget/Save", formData, function(result){}, "json");我的表單 (Form1) 為 Widget 上的每個屬性(Id、Name、Price)都有一個輸入欄位。這很好用,但它最終將 Widget 的每個屬性作為單獨的參數傳遞給我的控制器方法。
有沒有辦法我可以“攔截”數據,也許使用 ActionFilterAttribute,並在呼叫我的控制器方法之前將其反序列化為 Widget 對象?
謝謝杰夫,這讓我走上了正確的道路。DefaultModelBinder 足夠聰明,可以為我做所有的魔法……我的問題出在我的 Widget 類型上。在我匆忙中,我的類型被定義為:
public class Widget { public int Id; public string Name; public decimal Price; }請注意,該類型具有公共欄位而不是公共屬性。一旦我將它們更改為屬性,它就起作用了。這是正確工作的最終原始碼:
小元件.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; } } }