Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

c# - mvc Html.BeginForm different URL schema

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

@{
    Html.BeginForm("View", "Stations", FormMethod.Get);
}
@Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })
@{
    Html.EndForm();
}

If I choose a value from my dropdown I get redirected to the correct controller but the URL is not as I would like to have it:

/Stations/View?id=f2cecc62-7c8c-498d-b6b6-60d48a862c1c

What I want is:

/Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c

So how do I get the id= querystring parameter replaced by the more simple URL Scheme I want?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...