This example shows how to use Ajax in ASP. NET mvc4. The function is to implement message submission and backgroundProgramProcess the message and display the result on the front-end.
Running result:
MainCode:
Create. cshtml in views
Create a message form:
@ Using (html. beginform ("CREATE", "message", formmethod. Post, new {@ class = "keleyi "}))
{
<Table>
<Tr> <TD> title: </TD> <TD> @ html. Textbox ("ktitle") </TD> </tr>
<Tr> <TD> Email: </TD> <TD> @ html. Textbox ("kemail") for example: zhangsan@keleyi.com </TD> </tr>
<Tr> <TD> QQ: </TD> <TD> @ html. Textbox ("KQQ") </TD> </tr>
<Tr> <TD> content: </TD> <TD> @ HTML. textarea ("kcontent", new {rows = 10, cols = 50}) </TD> </tr>
<Tr> <TD> </TD> <button type = "Submit" id = "tijiao"> submit a message </button> <span id = "indicator" Style = "display: none "> </span> </TD> </tr>
</Table>
}
<Div id = "lastmessage"> </div>
The following describes how to use jquery's Ajax function to submit, process, and display messages:
<SCRIPT type = "text/JavaScript" src = "http://www.keleyi.com/keleyi/pmedia/jquery-1.9.1.min.js"> </SCRIPT>
$ (Document). Ready (function (){
$ ("Form. keleyi"). Submit (function (event ){
Event. preventdefault ();
Keleyiajax (this, update_sessions, "html ");
});
});
Function keleyiajax (Form, callback, format ){
$ ("# Indicator"). Show ();
$. Ajax ({
URL: form. Action,
Type: form. method,
Datatype: format,
Data: $ (form). serialize (),
Completed: $ ("# indicator"). Hide (),
Success: callback
});
}
Function update_sessions (result ){
$ ("Form. keleyi") [0]. Reset ();
$ ("# Lastmessage" cmd.html (result );
}
Process the messages submitted to the background:
Messagecontroler. CS
[Httppost]
Public string create (formcollection collection)
{
Return addmessage (Collection ["ktitle"], Collection ["kcontent"], Collection ["kemail"], Collection ["KQQ"]);
}
Private string addmessage (string ktitle, string kcontent, string kemail, string KQQ)
{
String k_message = "title:" + ktitle + "Email:" + kemail + "QQ:" + KQQ + "content:" + kcontent;
Return k_message;
}
Source codeDownload To http://keleyi.codeplex.com
More: http://www.keleyi.com/menu/mvc/
This article Reprinted from Ke leyi: http://www.keleyi.com/a/bjac/781ba7719ce323f.htm