MVC uses jQuery to pass a Model from a view to a controller.

Source: Internet
Author: User

There is a Model like this:

Using System. componentModel. dataAnnotations; namespace MvcApplication1.Models {public class Movie {public int Id {get; set;} [Required (ErrorMessage = "Required")] public string Title {get; set ;}}}

 

In HomeController, an Action is used to display a strong view, and a Model is used to receive the Model passed from the view.

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"});        }    }}

 

Method 1: Use the serialize () method of jQuery

@ Model MvcApplication1.Models. Movie @ {ViewBag. Title = "Index"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}< h2> Index 

 

Method 2: convert an anonymous object to JSON using the json. stringify () method of jQuery.

$ (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 ('submitted successfully ');}}});}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.