繁体   English   中英

有没有办法在MVC4 ActionLink中为其中一个RouteValue参数调用JavaScript?

[英]Is there any way to call JavaScript in an MVC4 ActionLink for one of the RouteValue parameters?

我的页面上有一个下拉列表(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调用中? 如果没有办法,或者不推荐,请告知另一种解决方案来解决这个问题? 提前致谢!

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

你可以通过使用javascript拦截链接来实现这一点Darin已经发布了一个这样的例子

但是,看起来您正在尝试使用ActionLink提交一些值,并且您可能最好创建一个包含所需值的viewmodel,然后使用提交按钮发布所有值。 这允许您发布比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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM