Several forms of passing parameters to the Controller in ASP. net mvc view, asp. netmvc
1. Pass the Array
$ (Function () {var value = ["C #", "JAVA", "PHP"]; $ ("input [type = 'click']"). click (function () {$. ajax ({url: "/Home/List", type: "Get", data: {valuelist: value}, traditional: true,// This attribute must be set; otherwise, the value cannot be obtained from the Controller.Success: function (data) {alert ("Success ");}});});});
public ActionResult List(List<string> valuelist) { return View(); }
Debugging results:
2. Pass a single Model
@ Using (Html. beginForm () {<div class = "form-group"> @ Html. labelFor (model => model. name, new {@ class = "control-label col-md-2"}) <div class = "col-md-10"> @ Html. editorFor (model => model. name) @ Html. validationMessageFor (model => model. name) </div> <div class = "form-group"> @ Html. labelFor (model => model. price, new {@ class = "control-label col-md-2"}) <div class = "col-md-10"> @ Html. editorFor (model => model. price) @ Html. validationMessageFor (model => model. price) </div> <div class = "form-group"> @ Html. labelFor (model => model. color, new {@ class = "control-label col-md-2"}) <div class = "col-md-10"> @ Html. editorFor (model => model. color) @ Html. validationMessageFor (model => model. color) </div> <div class = "form-group"> <div class = "col-md-offset-2 col-md-10"> <input type = "submit" value = "submit" class = "btn-default"/> </div>}
Public class Products {public int Id {get; set;} [DisplayName ("Product Name")] [Required (ErrorMessage = "this item cannot be blank")] public string Name {get; set;} [DisplayName ("product Price")] [Required (ErrorMessage = "this item cannot be blank")] public string Price {get; set ;} [DisplayName ("product Color")] [Required (ErrorMessage = "this item cannot be blank")] public string Color {get; set ;}}
public ActionResult Add(Products product) { return View(); }
Debugging results:
3. Pass Multiple Models
$ ("Input [type = 'submit ']"). click (function () {var promodes = []; promodes. push ({Id: "0", Name: "Mobile Phone", Color: "white", Price: "2499"}); promodes. push ({Id: "1", Name: "headset", Color: "black", Price: "268"}); promodes. push ({Id: "2", Name: "charger", Color: "yellow", Price: "99"}); $. ajax ({url: "/Home/List", type: "Post", data: JSON. stringify (promodes ),// Arrays must be serialized.ContentType: "application/json ",// Set the value of contentType to "application/json". The default value is "application/json"Success: function (data) {alert ("Success ");}});});
public ActionResult List(List<Products> valuelist) { return View(); }
Debugging results: