标签:c style class blog code java
有这样的一个Model:
using System.ComponentModel.DataAnnotations; namespace MvcApplication1.Models { public class Movie { public int Id { get; set; } [Required(ErrorMessage = "必填")] public string Title { get; set; } } }
HomeController中,一个Action用来显示强类型视图,一个用来接收从视图传递过来的Model。
using System.Web.Mvc; using MvcApplication1.Models; namespace MvcApplication1.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(new Movie()); } public ActionResult AddMovie(Movie movie) { return Json(new {msg = "ok"}); } } }
方法一:通过jQuery的serialize()方法
@model MvcApplication1.Models.Movie @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> @using (Html.BeginForm("AddMovie", "Home", FormMethod.Post, new {id = "addForm"})) { @Html.EditorFor(m => m.Title) @Html.ValidationMessageFor(m => m.Title) <br/> <input type="button" id="addMovie" value="提交"/> } @section scripts { <script src="~/Scripts/jquery.validate.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.js"></script> <script type="text/javascript"> $(function() { $(‘#addMovie‘).click(function(e) { e.preventDefault(); if ($(‘#addForm‘).valid()) { $.ajax({ url: $(‘#addForm‘).attr(‘action‘), type: $(‘#addForm‘).attr(‘method‘), data: $(‘#addForm‘).serialize(), success: function(data) { if (data.msg == ‘ok‘) { alert(‘提交成功‘); } } }); } }); }); </script> }
方法二:通过jQuery的 JSON.stringify()方法把匿名对象转换成json
$(function() { $(‘#addMovie‘).click(function(e) { e.preventDefault(); if ($(‘#addForm‘).valid()) { addMovie(); } }); }); function addMovie() { var movie = { "Title" : $(‘#Title‘).val() }; $.ajax({ url: ‘@Url.Action("AddMovie","Home")‘, data: JSON.stringify(movie), type: ‘POST‘, contentType: ‘application/json;charset=utf-8‘, success: function(data) { if (data.msg == ‘ok‘) { alert(‘提交成功‘); } } }); }
MVC使用jQuery从视图向控制器传递Model的2种方法,布布扣,bubuko.com
MVC使用jQuery从视图向控制器传递Model的2种方法
标签:c style class blog code java
原文地址:http://www.cnblogs.com/darrenji/p/3779038.html