mvc Html.BeginForm different URL schema

前端 未结 2 1886
自闭症患者
自闭症患者 2020-11-29 13:20

I\'m creating a form for a DropDown like this:

@{
    Html.BeginForm(\"View\", \"Stations\", FormMethod.Get);
}
@Html.DropDownList(\"id\", new SelectList(Vie         


        
相关标签:
2条回答
  • 2020-11-29 13:32

    Remove "id" from

    @Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })
    
    0 讨论(0)
  • 2020-11-29 13:42

    A form with FormMethod.Get will always post back the values of its form controls as query string values. A browser cannot generate a url based on your route configurations because they are server side code.

    If you really wanted to generate /Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c, then you could use javascript/jquery to build your own url and redirect

    @using (Html.BeginForm("View", "Stations", FormMethod.Get))
    {
        @Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"))
    }
    
    var baseUrl = '@Url.Action("View", "Stations")';
    $('#id').change(function() {
        location.href = baseUrl + '/' $(this).val();
    });
    

    Side note: Submitting on the .change() event is not expected behavior and is confusing to a user. Recommend you add a button to let the user make their selection, check it and then submit the form (handle the button's .click() event rather that the dropdownlist's .change() event)

    0 讨论(0)
提交回复
热议问题