我正在尝试从我的剃刀视图中提交ajax表单,我希望控制器返回一个JSON对象。当我使用(“#form0”)。submit(alert(“hi”););数据传到控制器,我收到警报。但是,当我使用(“#form0”)。submit(function(){alert(“hi”);});数据没有通过,我没有得到警报。我觉得这对我的语法来说是微不足道的,我很想念。这是相关的代码:
jquery的:
$(function () {
//setting up the schedule modal dialoag.
$("#schedModal").dialog({
buttons: {
Submit:
function () {
$("#form0").ajaxSubmit(function () {
//this is where I want to put the magic, but I need the alert to fire first.
alert("hi");
return false;
});
},
Cancel:
function () {
$(this).dialog("close");
}
},
autoOpen: false,
minHeight: 350,
modal: true,
resizable: false
});
目标观点:
@model FSDS.DataModels.Schedule
@using (Ajax.BeginForm("scheduleNew", null, new AjaxOptions { UpdateTargetId = "partial" }, new {}))
{
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.ScheduleName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ScheduleName)
@Html.ValidationMessageFor(model => model.ScheduleName)
</div>
@* tons of other labels and editor fields go in here, omitted for brevity. *@
}
控制器,如果重要:
[HttpPost]
public ActionResult scheduleNew(Schedule schedule)
{
if (Request.HttpMethod == "POST")
{
FSDSDBEntities context = new FSDSDBEntities();
if (ModelState.IsValid)
{
context.Schedules.AddObject(schedule);
context.SaveChanges();
}
return Json(schedule);
}
else
{
return PartialView();
}
}
答案 0 :(得分:2)
只需使用$('#form0').submit();
:
Submit: function () {
$('#form0').submit();
}
然后在AjaxForm中定义一个OnSuccess
处理程序,当AJAX请求成功时将调用该处理程序:
@using (Ajax.BeginForm("scheduleNew", null, new AjaxOptions { OnSuccess = "success", UpdateTargetId = "partial" }, new {}))
最后success
javascript处理程序:
function success(data) {
// the form was successfully submitted using an AJAX call.
// here you could test whether the data parameter
// represents a JSON object or a partial view
if (data.ScheduleName) {
// the controller action returned the schedule JSON object
// => act accordingly
} else {
// the controller action returned a partial view
// => act accordingly
}
}