Preface: Writing this essay, the URL of the omission of the slash, looking for a long time error, the whole people are very bad. #我是猪系列
Background: A previous article on how to build an ASP. Mvc4&jquery&ajax&json example, which explains how to pass and process data between view and action.
1, foreground HTML code:
1 <div>2 <button type="button" id="btn" > Passing data from the view to the controller </button>3 <p id="info"></ P>4 </div>
View Code
2, front desk JS code:
1$("#btn"). Click (function () {2 $.ajax ({3 Async:true,4Type"POST",5Url:"/ajaxtest/ajaxbackdata",6Cachefalse,7 data: {8Name:"SHARPL", City:"Beijing", Age: -9 },Ten success:function (Result) { One$("#info"). Text (result); A } - }); -});
View Code
JS Code Explanation: Note the URL: "/ajaxtest/ajaxbackdata", ajaxtest before the '/' must not miss, Bo Master has begun to suspect life.
Data: {Name: "Sharpl", City: "Beijing", age:18}, this is the way to pass the past as an anonymous object.
Or JS code to write like this:
1 $ (function () {2$("#btn"). Click (function () {3 vardata ="";4Data + ="&name="+encodeuri ("SHARPL");5Data + ="&age="+ encodeURI ( -);6Data + ="&city="+ encodeURI ("Beijing");7 $.ajax ({8 Async:true,9Type"POST",TenUrl:"/ajaxtest/ajaxbackdata", OneCachefalse, A Data:data, - success:function (Result) { -$("#info"). Text (result); the } - }); - }); -});
View Code
The results are exactly the same.
3, the background code is as follows:
1 Publicactionresult Ajaxbackdata (STU STU)2 {3 stringName =Stu. Name;4 intAge =Stu. Age;5 stringCity =Stu. City;6 stringtmp=string. Format ("{0} age {1} years, from {2}", name,age,city);7 returnContent (TMP);8}
View Code
Note that the action parameter is Stu, which directly obtains the data that is passed in Ajax mode.
Or the background code is as follows: (classic method used in the project)
1 Publicactionresult ajaxbackdata ()2 {3 varStu =NewSTU ();4 This. Updatemodel (Stu);5 stringtmp=string. Format ("{0} age {1} years, from {2}", Stu. Name,stu. Age,stu. City);6 returnContent (TMP);7}
View Code
。。。
Of course not necessarily in the form of content, return to the results of processing to view, but my neck is too painful, so first go to bed
How to pass data in the view and action in an AJAX fashion in ASP.