MVC使用jQuery从视图向控制器传递Model的2种方法

有这样的一个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('提交成功');
                    }
                }
            });
        }
posted @ 2014-06-09 23:35  Darren Ji  阅读(1299)  评论(0编辑  收藏  举报

我的公众号:新语新世界,欢迎关注。