栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用JSON将复杂类型传递给ASP.NET MVC控制器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用JSON将复杂类型传递给ASP.NET MVC控制器

谢谢杰夫,这使我走上了正确的道路。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; }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614049.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号