The model that needs to be passed through jquery to the controller method is:
Public class Person
{
Public string Name {get; set;}
Public int
}
use the Message property of the following class to load a success or error message, and eventually convert it to JSON format to return to the view:
Public class Personvm
{
Public string
}
The controller displays error messages by traversing the Modelstate.keys.
Public ActionResult Demo ()
{
return View ();
}
[HttpPost]
Public ActionResult Saveperson (person person)
{
if (Modelstate.isvalid)
{
string string. Format ("user name: {0}, Age: {1}", Person.) Name, person. Age);
return Json (new PERSONVM () {message = message});
}
Else
{
string "<div class=\" Validation-summary-errors\ "> The following error:<ul> occurred";
foreach inch Modelstate.keys)
{
var error = Modelstate[key]. Errors.firstordefault ();
if null)
{
"<li class=\" field-validation-error\ ">" +error. errormessage+"</li>";
}
}
"</ul>";
return Json (new PERSONVM () {Message = errormessage});
}
}
The view uses the $.tojson () method to convert the model to a JSON format and pass it to the Controller method. Convert the object into a JSON-formatted jquery extension, here.
@model MvcApplication1.Models.Person
@{
"Demo";
"~/views/shared/_layout.cshtml";
}
@Html. Editorformodel ()
<input type="Submit"value="Save" id="personcreate"/>
<div>
<span id="Resultmessage"></span>
</div>
@section scripts
{
<script src="~/scripts/json.js"></script>
<script type="Text/javascript">
$ (function () {
$ (' #personCreate '). Click (function () {
var person = Getperson ();
if null) {
Alert ("user name cannot be empty");
return;
}
var json = $.tojson (person);
$.ajax ({
' @Url. Action ("Saveperson", "Home") ',
' POST ',
' json ',
Data:json,
' Application/json; Charset=utf-8 ',
Success:function (data) {
var message = data. Message;
$ ("#resultMessage"). HTML (message);
}
});
});
});
function Getperson () {
var name = $ (' #Name '). Val ();
var age = $ (' #Age '). Val ();
return "" null : {name:name, age:age};
}
</script>
}