在ActionLink上持久化数据单击MVC3
本文关键字:单击 MVC3 数据 持久化 ActionLink | 更新日期: 2023-09-27 18:21:13
单击时,我正在使用@Html.ActionLink("Home", "Home")
当前传递回"主页"。然而,当点击动作链接时,是否可以让页面在自己身上执行帖子(即在控制器中点击其帖子事件)。
我基本上需要一种导航到页面的方法,但首先要将所有当前页面数据提交到模型中。
注意:忘记添加ActionLink
在页面的partialView内
您可以使用AjaxHelper
方法ActionLink()
提交当前页面的POST
。然后,对于控制器中的HttpPost
操作方法,只需重定向到Home
即可。
类似这样的东西:
您的视图
@Ajax.ActionLink("Click me", "SubmitMe", "Current", new AjaxOptions() { HttpMethod = "Post" })
您的控制器
public class CurrentController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SubmitMe(SomeModel someModel)
{
// do what you have to do here
return RedirectToAction("Home", "Home");
}
}
您可以使用javascript(我建议使用jQuery)提交表单,然后重定向。您还可以提交表单,并在[HttpPost]
修饰的Actionmethod中使用RedirectToAction()
。
jQuery示例
$(function() {
$("#YourButton").click(function(e) {
e.preventDefault();
$.post("YourUrlToPostTo", $("#yourForm").serialize(), function() {
// success, redirect now
});
});
});
您不能以这种方式使用操作链接。您可以使用jQuery创建JSON对象,或者字符串化表单的内容,然后通过将方法设置为POST来调用.ajax()方法。
您的jQuery代码可能如下所示:
$('#yourActionLink').click(function(e) {
e.preventDefault();
var yourValues = $("form").serialize();
$.post($(this).attr("href"), yourValues, function() {
alert("Data saved.");
});
});
应该是这样的。