是否有任何方法在MVC4 ActionLink中调用一个RouteValue参数

asp.net mvc - Is there any way to call JavaScript in an MVC4 ActionLink for one of the RouteValue parameters?

本文关键字:一个 参数 RouteValue 调用 任何 方法 ActionLink MVC4 是否      更新时间:2023-09-26

我有一个下拉列表(DropDownListFor)和一个ActionLink在我的页面。基本上,我遇到的问题是我试图从下拉列表中捕获选定的值并将其作为ID传递给我的ActionLink。下面是我的代码:

@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拦截链接来做到这一点Darin已经发布了一个这样的例子。

然而,它看起来像你试图使用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();
}

您可以像这样为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);
});