我有view
请求用户输入。 View
如下所示 -
@(Html.Input(m => m.SchoolName).Id("SchoolName"))
@(Html.Input(m => m.Address).Id("Address"))
@(Html.Input(m => m.Phone).Id("Phone"))
<button class="btn btn-primary" name="btnSchoolSave" id="btnSave">
Submit
</button>
然后我有一个javascript函数,它处理按钮的click
事件 -
function () {
$("button[name='btnSchoolSave']").on('click', function () {
$.ajax({
url: '/School/SaveSchool', //School is my controller and 'SaveSchool' is the method in the controller.
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html'
})
.success(function (result) {
alert("saved")
})
.error(function (xhr, status) {
alert(status);
})
})
};
我的控制器方法如下所示。我还没有实现这个方法。
public void SaveSchool(Models.School model)
{
//TODO
}
我的想法是 - 我想获取用户在View中输入的所有值,获取所有这些Model值,并将其传递给Javascript函数,javascript函数返回将Model传递给控制器方法并保存。
现在,我知道我可以直接从视图中调用我的Controller操作方法,并获得保存的数据。但是,我的要求是将数据传递给javascript,并从javascript调用方法并保存用户输入。
我该怎么做?
由于
答案 0 :(得分:0)
@model XXX.YourViewModel
<form id="your-form" style="margin: 0px;">
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.Id)
@Html.LabelFor(m => m.SchoolName)
@Html.TextBoxFor(m => m.SchoolName)
@Html.ValidationMessageFor(m => m.SchoolName)
@Html.LabelFor(m => m.Address)
@Html.TextBoxFor(m => m.Address)
@Html.ValidationMessageFor(m => m.Address)
@Html.LabelFor(m => m.Phone)
@Html.TextBoxFor(m => m.Phone)
@Html.ValidationMessageFor(m => m.Phone)
<button id="btnSchoolSave" name="edit" type="button">Save</button>
</form>
$("#btnSchoolSave").on('click', function () {
//get the form
var form = $("#your-form");
//validate form
if (!form.valid()) {
return;
}
//serialize the form
serializedForm = form.serialize();
//ajax post
$.ajax({
url: "@Url.Action("CompanyEdit", "CV")",
type: "POST",
data: serializedForm
.........
......
现在serializedForm将作为ViewModel
发布到您的控制器参数[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSchool(YourViewModel modal)
{
//find school
var school = repository.FindSchool(modal.Id)
//map value from modal
school.SchoolName = modal.SchoolName;
..........
repository.SaveScool(school);
}