asp.net MVC foreground View page several ways to pass data to the back desk controller controller

Source: Internet
Author: User
Tags html tags modifier

Previous article asp.net mvc @model and model explain how the background controller to the front page to pass data, and today we will explain the front view page back to the table controller controller to pass data several ways. These are some of the ways I use in practice and summed up, if that place is wrong or have deficiencies, you are welcome to point out and give constructive advice, and learn together.

1, asynchronous mode

In actual project development, we often need to submit data asynchronously, we can get some important information without submitting the current page. This will neither waste network resources nor cause server load. The main asynchronous methods are Ajax, post, get three kinds of

(1) Ajax Way

/* To determine whether the user has logged on/
        $ (function () {
            $.ajax ({
                type: "Post",
                URL: "/MONTHWIN/INDEX/12",
                data:{"name": Name, "Sex": Sex},
                dataType: ' JSON ',
                success:function (result) {
                    if (result = = True) {
                        IsLogin = True;
  }
                    Else {
                        islogin = false;}}}
        )

(2) Post mode

        $.post (URL, {"username": Username, "province": Province, "City": City, "branch": Branch, "number": Number, "Bankname": Ba Nkname},
                       function (result) {
                           if (result = = "1") {
                               alert ("Saved successfully");
                               Location.reload ();
                           }
                           else {
                               alert ("Save Failed");
                               Location.reload ();
                           }
                       );

Summary: The asynchronous approach is also simpler to implement, of course, this is only one aspect. The most important point is that the value can be returned. We can do the next step based on the values passed in the background, while reducing the server request and reducing the network load.

2. Form mode

(1) Post mode

<1> post way without JS, direct submission

<form onsubmit= "Layer.load (' Submit in Request ')" action= "/WITHFUNDING/STARTFUNDING/12" method= "POST" > <input type= " Hidden "Name=" CategoryID "value=" "/> <input type=" hidden "name=" Accountmoney "value=" @ViewBag. Account "/> & Lt;input type= "hidden" name= Totalfreezemoney "value=" @ViewBag. Totalfreezemoney "/> <input type=" hidden "name=" Totalwithfunding "Value=" @ViewBag. totalwithfunding "/> <input type=" hidden "name=" Totaldepositmoney "value=" @ Viewbag.totaldepositmoney "/> <input type=" hidden "name=" Moneydeposit "value=" @ViewBag. Moneydeposit "/> < Input type= "hidden" name= "moneywithfunding value=" @ViewBag. moneywithfunding "/> <input type=" hidden "name="
Rateopen "Value=" @ViewBag. Rateopenline "/> <input type=" hidden "name=" Ratewarn "value=" @ViewBag. Ratewarn "/>" <input type= "hidden" name= "Defaultmanagemoney" value= "@ViewBag. Defaultmanagemoney" id= "Managemoney"/> < Input type= "hidden" name= "StartTime" value= "@ViewBag. StartTime"/> <iNput type= "hidden" name= "Managefeerate" value= "@ViewBag moneyrate"/> <input "type=" hidden "Days" name= "Days" /> <input type= "button" onclick= "History.go ( -1)" value= "Back to modify" class= "btn2"/> </form>

<2> Post method with JS submission

   * * Modify bank card/
   function Updatebank () {
       var username = $.trim ($ ("#username"). Val ());
       var branch = $.trim ($ ("#branch"). Val ());
       var number = $.trim ($ ("#changbankno"). Val ());
       var check =/^ (\d{19}) $/;
       var bankname = $ ("#addBankCode"). Find ("option:selected"). Text ();
       if (username = = "" | | Username = = NULL) {
           alert ("Please enter account name");
       }
       else if (branch = "" | | Branch = = NULL) {
           alert ("Please enter the Account branch");
       }
       else if (number = = "" | | Number = null) {
           alert ("Please enter bank card numbers");
       }
       else if (!check.test (number)) {
           alert ("Please enter the correct bank card format");
       }
       else if (bankname = "Please select Bank") {
           alert ("Please select Bank");
       }
       else {
           $ (' #Updatebank '). Submit ();
       
   

The two forms of form submission described above can only be submitted in a simple backward way, and we cannot see the return value of the server after the data is submitted. In order to get the result, we also need to add code in the background. This is no longer a tiring statement here.

Summary: From the above code we can see that the post can pass the value of the data is almost unlimited, if the need for a large number of values, post method is a good choice.

(2) Get mode

Form submission can also be referred to as the QueryString way, is simply put the data to be passed after the URL.

<form onsubmit= "Layer.load (' Submit in Request ')" action= "/withfunding/startfunding/12?id=123" method= "Get" ></form >

Summary: But get method has a lot of disadvantages compared to post: The amount of data transfer is limited, unsafe

Of course in MVC we can also implement form submission via HTML helper, not in here, please refer to: MVC Learning Series-html Helper Usage

3. Asynchronous Form Mode

//the asynchronous commit event for the MyForm binding Ajaxform and provides a simple callback function.
            $ (' #myForm '). Ajaxform (function () { 
                alert ("Thank for Your comment!") 
    ;}); </script> 
Summary: This way is the combination of the first two ways, of course, the combination of the advantages of both, more convenient

4 model mode of data storage

The model in MVC is a bridge between controller and view, and of course it can pass data between view and controller. The implementation of this approach is mainly divided into the following three steps:

(1) Define model entity

public class Model
{public
string Rtonumber {set; get;}
public string Approver {set;
public string modifier {set;
public string Comment {set;
}

(2) Define HTML tags

<div id= "Container" >
<table id= "table" >
<tr>
<td>& Lt;label>rtonumber</label><input name= "Rtonumber"/></td>
<td><label> Approver</label><input name= "Approver"/></td>
<td><label>modifier</l Abel><input name= "modifier"/></td>
<td><label>comment</label><tex Tarea name= "comment" cols= "rows=" "4" ></textarea></td>
</tr>
</table >
<input id= "Submit" type= "button" value= "Submit"/>
</div>

(3) Transfer value

<script type= "Text/javascript" > $ (Function () {$ (' #submit '). Click (function () {
                var model = [];
                var submodel = [];
                    $.each ($ ("Table tr"), function (I, item) {var Rtonumber = $ (item). FIND ("[Name=rtonumber]"). Val ();
                    var approver = $ (item). FIND ("[Name=approver]"). Val ();
                    var Modifier = $ (item). FIND ("[Name=modifier]"). Val ();
                    var Comment = $ (item). FIND ("[Name=comment]"). Val ();
                Model.push ({rtonumber:rtonumber, approver:approver, Modifier:modifier, Comment:comment, Checkboxvalue:submodel});
                });
                    $.ajax ({url: '/withfunding/startfunding ', data:JSON.stringify (model), Type: ' POST ', ContentType: ' Application/json;charset=utf-8 ', async:fals
E, success:function (data) {                        Alert ("Postting data is over!");
            }
                });
        });
}); </script>
Conclusion: In the data storage model, we also use the Ajax asynchronous method. However, this approach is different from the AJAX approach: The data passed is the model entity type. I believe you also see, although model can realize view transfer value to controller, but the code is larger, and not very good understanding, so in practice we do not use much.

5. Url Routing method

In the MVC development approach, we're asking for an action under the controller, and sometimes the action requires a parameter, which is the routing parameter. We pass route parameters by adding routing rules.

        public static void RegisterRoutes (RouteCollection routes)
        {
            routes. Ignoreroute ("{resource}.axd/{*pathinfo}");

            Routes. Maproute (
                "Default",//Route name
                "{controller}/{action}/{id}",//URL with parameters
                New {controller = "H ome ", action =" Index ", id = urlparameter.optional}//Parameter defaults
            );
        }
The URL route pass value is shown below

Http://localhost:39901/UserPay/Withdraw/12
The 12 above is the routing parameter, and the corresponding action is shown below
        Public ActionResult withdraw (int id) {int Cid = 0; var Mid = Webhelper.getcookie (StockFunds.Key.CookieKey.MemberId);//user ID if (!string.
            Isnullorwhitespace (mid)) {cid= Convert.ToInt32 (Securehelper.aesdecrypt (mid));
            } string Username = request["Username"];
            String province = request.form["province"];
            String city = request["City"]; String branch = request["Branch"];//sub-branch = request["number"];//card numbers string bankname = Re
            quest["Bankname"];//Account Bank = new F_member_banks (); Bank.
            Bankname = Bankname; Bank.
            Bankno = number; Bank.
            MId = Cid; Bank.
            cardholder = Username; Bank.
            Adddate = System.DateTime.Now; Bank.
            Accountbranck = Branch; var res = BLL. F_MemberBLL.GetMember.BandBinding (Bank).
            ToString (); ReturnContent (RES); }

Summary: URL routing mode of data transmission is very limited, not suitable for the transfer of large amount of data.

Above only explained the foreground to the backstage to pass the value the several ways, the concrete backstage how accepts the data to be no longer explained. Hope to be helpful to everyone.

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.