標籤:style blog class code java c
需要通過jquery傳遞到控制器方法的Model為:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
使用下面這個類的Message屬性裝載成功或錯誤資訊,並最終轉換成json格式返回給視圖:
public class PersonVm
{
public string Message { get; set; }
}
控制器通過遍曆ModelState.Keys來顯示錯誤資訊。
public ActionResult Demo()
{
return View();
}
[HttpPost]
public ActionResult SavePerson(Person person)
{
if (ModelState.IsValid)
{
string message = string.Format("使用者姓名:{0},年齡:{1}", person.Name, person.Age);
return Json(new PersonVm() {Message = message});
}
else
{
string errorMessage = "<div class=\"validation-summary-errors\">發生以下錯誤:<ul>";
foreach (var key in ModelState.Keys)
{
var error = ModelState[key].Errors.FirstOrDefault();
if (error != null)
{
errorMessage += "<li class=\"field-validation-error\">"+error.ErrorMessage+"</li>";
}
}
errorMessage += "</ul>";
return Json(new PersonVm() {Message = errorMessage});
}
}
視圖使用 $.toJSON()方法,把Model轉換成json格式傳遞給控制器方法。把對象轉換成json格式的jQuery擴充,在這裡。
@model MvcApplication1.Models.Person
@{
ViewBag.Title = "Demo";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.EditorForModel()
<input type="submit" value="儲存" 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 (person == null) {
alert("使用者名稱不可為空");
return;
}
var json = $.toJSON(person);
$.ajax({
url: ‘@Url.Action("SavePerson","Home")‘,
type: ‘POST‘,
dataType: ‘json‘,
data: json,
contentType: ‘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 (name == "") ? null : { Name: name, Age: age };
}
</script>
}