ASP.Net MVC ActionLink

时间:2009-06-04 12:08:49

标签: asp.net-mvc

我正在尝试在我的一个视图中创建一个ActionLink,它将下拉列表的选定值发送到新操作。到目前为止,我有这个,我只需要找到一种方法来填充我的ActionLink末尾的ID。

   <%= Html.DropDownList("StatusDropDown") %>
   <%= Html.ActionLink("Apply","Index",new {Controller="Tasks", Action="Index", id="DROPDOWN LIST SECLECTED VALUE"}) %>

显然,只要更改了下拉列表的选定索引,就需要更新此链接。这是我需要在javascript中做的事情,还是有更好的方法从ASP.Net MVC中管理它?

由于

2 个答案:

答案 0 :(得分:2)

如果您不想使用表单提交(即,希望将参数作为url的一部分而不是表单参数传递),则需要使用javascript构建url客户端。

<%= Html.DropDownList("StatusDropDown") %>
<a id="applyLink" href="#">Apply</a>

<script type="text/javascript">

    function setHref( elem, val )
    {
        if (val) {
           $(elem).attr( "href", "/Tasks/" + val );
           $("#applyLink").unbind("click");
        }
        else {
           $(elem).attr( "href", "#" );
           $("#applyLink").click( function() { alert( "No value chosen" ); } );
        }
    }

    $(function() {
       var dropdown = $("#StatusDropDown");
       dropdown.change( function() {
           setHref( this, $(this).val() );
       });
       setHref( dropdown, null );
    });
</script>

答案 1 :(得分:0)

链接转到另一个页面,它实际上是一个重定向。参考下拉列表更新链接所在位置的唯一方法是使用javascript。

听起来你想要一种提交动作。在这种情况下,您应该使用表单和提交按钮,在控制器中创建适当的处理程序。请记住,您可以根据提交的表单值在控制器中进行重定向。所以像这样:

<form method="post" action="/MyForm">
    <input type="select" name="mySelect">
        <option value="1">First Option</option>
        <option value="2">Second Option</option>
    </input>
</form>

在你的控制器中:

public ActionResult MyForm(int mySelect)
{
    return Redirect(String.Format("myurl?id={0}", mySelect));
    // Note the above is only preferable if you're going to an external link
    // Otherwise you should use the below:
    return RedirectToAction("myAction", new { id = mySelect });
}

显然,在这个简化的示例中,您所需操作的MyForm代理是多余的,但它说明了这个想法,因此您可以将其应用于您的特定情况。