我有按钮 - 一个子提交和一个用于取消。前者是表单旁边的常用输入控件。
@Html.ActionLink(" ", "List", "Home", null, new { @class = "cancel" })
<input type="submit" value="Save" />
以上工作正常。但是,我对代码的外观不满意,所以我尝试使用 ActionLink 来执行这两个事件,就像这样。
@Html.ActionLink(" ", "List", "Home", null, new { @class = "cancel" })
@Html.ActionLink(" ", "Save", "Home", null, new {
@class = "submit",
onclick = "javascript:document.forms[0].submit()" })
当我执行它时,我在 Controller 上遇到了一个问题,但是传回的模型是空的(即所有字段都是默认值)。我猜测操作链接会将我从表单上下文外部发送到保存,但我不知道如何让它不这样做。
至少,我希望该页面发送两次 调用。一个基于通过 ActionLink 的 href 的虚拟模型,第二个由正在执行的 JS 调用。
如何让它发挥作用?有更好的方法吗?主要是,我不想设置input 控件的样式。我更喜欢为 Html.ActionLink 生成的链接设置样式。
最佳答案
Html.ActionLink
生成一个 anchor 标记,点击它通常会生成一个 GET 请求。通常,您不能使用它提交表单数据。
您可以做的是,当用户点击您的链接时,使用 javascript-jQuery,使用 jQuery serialize()
方法序列化表单并使用 ajax 发送它。
@using(Html.BeginForm())
{
<label>Name </label> @Html.TextBoxFor(s=>s.FirstName)
@Html.ActionLink("Save","Save","Home",null,new { class="sbmt" })
}
这将在您的表单标签内生成一个带有 css 类 sbmt 的 anchor 标签,并在您的 javascript 中监听带有此 css 类的 anchor 标签上的 click
事件。
$(function(){
$("a.sbmt").click(function(e){
e.preventDefault(); // prevent default form submit behaviour since we are doing ajax
var _f=$(this).closest("form");
$.post(_f.attr("action"),_f.serialize(),function(res){
//do something with the response coming back from your Save action method.
if(res.status==="success")
{
alert("Saved");
// If you want to reload the page, you can do this
window.location.href=window.location.href;
}
});
});
});
由于我们发出的是 ajax 请求,因此从操作方法返回 json 响应是个好主意。
[HttpPost]
public ActionResult Save(YourViewModel model)
{
// Save
if (Request.IsAjaxRequest())
{
return Json(new {status="success"});
}
return RedirectToAction("Index"); //if not an ajax request, do the redirect
}
关于javascript - 如何使用 ActionLink 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34579684/