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(提交成功);
                    }
                }
            });
        }

MVC使用jQuery从视图向控制器传递Model的2种方法,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。