【发布时间】:2014-09-22 20:30:54
【问题描述】:
要提交下面的表单,我必须点击下面粘贴的表单底部的<input type="submit" value="Save" />:
@model WebApplication2.Models.Person
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Save" class="btn btn-success" style="width: 200px; font-weight: bold;" />
</div>
</div>
</div>
}
这会导致在PersonController 中调用POST Edit 方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName")] Person person) {
if (ModelState.IsValid) {
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
我也想要一个 JavaScript 函数,它做同样的事情(当我调用这个函数时)但不会将我重定向到任何视图。只需调用POST Edit 并传递上述表单的内容。
问题:如何编写 JavaScript 函数来提交上面的表单而不会将我重定向到任何地方?
function SubmitForm() {}
编辑
我试过这个。
当我点击@Html.ActionLink("Add a Report", "Create", "Reports", new { personId = Model.Id }, new { onclick = "SubmitForm()" })时调用了JavaScript方法(显示警报)但没有提交表单(标准提交按钮有效,因此是JavaScript函数错误)。
表格:
@using (Html.BeginForm(null, null, FormMethod.Post, new { name="myForm", id = "myForm" })) {
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>
<p> @Html.ActionLink("Add a Report", "Create", "Reports", new { personId = Model.Id }, new { onclick = "SubmitForm()" })</p>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Save" class="btn btn-success" style="width: 200px; font-weight: bold;" />
</div>
</div>
</div>
}
和功能:
function SubmitForm() {
alert("IS INVOKED");
$("#myForm").submit();
}
【问题讨论】:
标签: javascript asp.net-mvc forms razor