MVC passes data-passing objects or collections of objects

Source: Internet
Author: User

Objective

This article focuses on submitting objects or collections of objects from a view (or JS) file to a controller, such as submitting a row of data from a table as an object, or submitting multiple rows of data as a collection to a controller.

Review

To submit data to a controller from a view (or JS) file, you may have seen several ways:

    • Append the submitted data to the URL address
 $.ajax ({type: " POST ", url: "/invitebid/updatebidzrecord/?                                Judgebidid= " + judgebidid + " &bidrecordid= " + Bidrecordid, Success: function   (JSO Nresult)  {}, Error: function   { $.messager.alert (
     
       "hint" 
     ,  "Evaluation Method submission failed!                    ", " warning ");                return ; }            });
    • the use of routing with Parameters (The default route, the passed parameter is the ID)

Open the Global.asax.cs file in the client, and you will see the following code:

publicstaticvoidRegisterRoutes(RouteCollection routes)        {            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            routes.MapRoute(                "Default"// 路由名称                "{controller}/{action}/{id}"// 带有参数的 URL                new"Home""Index"// 参数默认值            );        }

This is the default route, and of course you can write a custom route. This default route determines that you can pass the value in the following way and receive it in the controller.

$(‘#dg ‘).datagrid({                url:‘/EvaluationTotalScore/GetTotalScoreDataByMore/‘Id            });

With the "/" way, the parameters are attached to the URL, it looks simple and neat. You can only pass one parameter for this default route, and you must name the parameter name ID.
In the controller, the parameters of the action method are received:

publicGetTotalScoreDataByMore(string Id)        {        }
Main content
    • Passing objects from view to controller
$.ajax ({type:"POST", Async:falseUrl:"/invitebid/updatetruescore", ContentType:"Application/json",//must have, indicating the type of data submittedDataJSON. stringify ({"Bidjudgeviewmodel":                    [{' Bidrecordid ': Bidproid,' Judgeid ': Editingid,' Truescore ': Score}]}), success: function (Result) {$.messager.alert ("Hint","Congratulations, the change is successful!" ","Info"); }, Error: function (data) {$.messager.alert ("Hint","Sorry, the modification failed, please try again later!" ","Warning");return; }        });
    • To pass a collection of objects from a view to a controller
   if(document.getElementById (selrow[i). Judgeid)! =NULL) {if(document.getElementById (selrow[i). Judgeid). Checked) {varCheckrow = Selrow[i];//Instantiate a scoring project object                    varJudgeitemviewmodel = {JudgeId:checkRow.JudgeId, JudgeItemName:checkRow.Ju Dgeitemname, JudgeItemContent:checkRow.JudgeItemContent, Requirement:check Row.requirement, Score:checkRow.Score};//Add an object to the arrayArrayjudgeitems.push (Judgeitemviewmodel); }            }        }//Submit data$.ajax ({type:"POST", Async:falseUrl:"/invitebid/addbidjudgeitem", ContentType:"Application/json",//must have, indicating the type of data submittedDataJSON. Stringify (Arrayjudgeitems), success: function (Result) {$.messager.alert ("Hint","Congratulations, your choice to save success!" ","Info"); }, Error: function (data) {$.messager.alert ("Hint","Sorry, your choice save failed, please try again later!" ","Warning");return; }        });

When you pass multiple rows of data, you take advantage of an array of objects, and then similarly, serialize by Json.stringify.
When receiving in a controller, the method is the same as the type name of the element in the list in the parameter and the name of the object in the view, as in this case called Judgeitemviewmodel:

  publicvoidAddBidJudgeItem(List<JudgeItemViewModel> JudgeItemViewModel)         {        }
Summarize

  There are two methods of JSON objects: Stringify () and parse (). In the simplest case, these two methods are used to serialize the JavaScript object to a JSON string and parse the JSON string into native JavaScript. It is useful to use the stringify () method to transfer objects or collections of objects to better reflect the encapsulation of the data.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

MVC passes data-passing objects or collections of objects

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.