有没有办法在MVC4 ActionLink中为一个RouteValue参数调用JavaScript?
我在页面上有一个下拉列表(DropDownListFor)和一个ActionLink。基本上,我遇到的问题是我试图从我的下拉列表中捕获选定的值,并将其作为ID传递给我的ActionLink。这里是我的代码:有没有办法在MVC4 ActionLink中为一个RouteValue参数调用JavaScript?
@Html.DropDownListFor(x => x.Capsules, new SelectList(Model.Capsules, "pk", "name", "pk"))
<br />
@Html.ActionLink("Submit", "Create",
new { controller = "Process", id = /*JavaScript here to get the selected ID for the DropDownList above*/ },
new { data_role = "button" })
对于什么,我要完成的,是有办法的JavaScript嵌入到我的Html.ActionLink电话?如果没有办法,或者不推荐,可否请您提供另一种解决方案来解决这个问题?提前致谢!
您可以通过使用JavaScript达林有这个posted an example拦截的链接做到这一点。
但是,它看起来像是在尝试使用ActionLink提交一些值,并且您最好创建一个包含所有想要的值的视图模型,然后使用提交按钮发布所有内容。这允许您发布更多的数据而不仅仅是ID,防止您依赖Javascript,并且保留所有的代码服务器端而不是混合和匹配。
通过您发布的小代码判断 - 您已经有了一个模型,可能是一些强类型实体,并且它有一个名为Capsules的属性。
在你的控制,创造出拥有视图的数据视图模型:
public class YourViewModel
{
YourModel YourModel { get; set; }
public int CapsuleId { get; set; }
}
那么你的观点:
@using(@Html.BeginForm("Create", "Process" ))
{
@Html.DropDownListFor(m=> m.CapsuleId, new SelectList(Model.YourModel.Capsules, "pk", "name", "pk"))
<input type="submit">
}
那么你的控制器动作来处理这个问题:
[HttpPost]
public ActionResult Create(YourViewModel model)
{
var id = model.CapsuleId;
// do what you're going to do with the id
return View();
}
这看起来很有前途。今晚晚些时候我会试着实施你的建议!谢谢!! – 2013-02-28 18:17:50
你可以把假值这样的id
参数:
@Html.ActionLink("Submit", "Create",
new { controller = "Process", id = "dummy" },
new { data_role = "button" })
然后替换值单击链接时。
// Assuming your link's id is `submit`, and the dropdown's id is `capsules`
$('#submit').click(function() {
var id = $('capsules').val();
$(this).href = $(this).href.replace('dummy', id);
});
不幸的是,这不适合我。传递到下一页的值是-1。即使用实际值代替“id”,在我的情况下,“3”。它没有对我的网址做任何事情。 – 2013-02-27 04:31:11
你有调试javascript吗?当你的链接被点击时它会被调用吗? – 2013-02-27 04:32:40
我一直都很难调试JavaScript,所以我不确定。这种方式似乎是一种解决方法...我想我以后是有一个共同的,记录的方式来做到这一点?或者解决方法是唯一的选择? – 2013-02-27 04:36:02
你用剃刀吗? – 2013-02-27 04:12:49
是的,我正在使用剃须刀。 – 2013-02-27 04:13:33