There is a model like this:
usingSystem.ComponentModel.DataAnnotations;namespacemvcapplication1.models{ Public classMovie { Public intId {Get;Set; } [Required (ErrorMessage="must fill in")] Public stringTitle {Get;Set; } }}
In HomeController, an action is used to display a strongly typed view, one to receive the model passed from the view.
usingSYSTEM.WEB.MVC;usingMvcapplication1.models;namespacemvcapplication1.controllers{ Public classHomecontroller:controller { PublicActionResult Index () {returnView (NewMovie ()); } Publicactionresult Addmovie (movie movie) {returnJson (New{msg ="OK"}); } }}
Method One: Through the Serialize () method of jquery
@model mvcapplication1.models.movie@{viewbag.title="Index"; Layout="~/views/shared/_layout.cshtml";}@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="Submit"/>} @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 ('Submit Success'); } } }); } }); }); </script>}
Method two: Using JQuery's Json.stringify () method to convert an anonymous object to JSON
$ (function () {$ ('#addMovie'). Click (function (e) {e.preventdefault (); if($('#addForm'). Valid ()) {Addmovie (); } }); }); function Addmovie () {varMovie = { "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 ('Submit Success'); } } }); }