MVC URL routing to target specific urls [duplicate] - asp.net-mvc

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?

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)

Remove "id"
from
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })

Related

ASP Route Data attribute in HTML Actionlink

I have a href attribute using anchor tag helper asp-all-route-data. I want to change this to use HTML.ActionLink that has a onclick popup message but not sure how to do it.
I have tried this so far:
#Html.ActionLink("Set as Draft", "SetAsDraft", "Item", new {
FromRouteAttribute = "setAsDraftParams" },
new { onclick = "return
confirm('Are sure you want to set this Item as a draft?');" })
Current a href:
<a asp-area="Admin" title="Set as Draft DOR" asp-controller="Dor" asp-
action="SetAsDraft" asp-all-route-data="setAsDraftParams">Set as Draft
DOR</a>
Variable set in the View:
var setAsDraftParams = new Dictionary<string, string>
{
{ "id", Model.DraftToView.ItemId.ToString() },
{ "returnViewName",
nameof(Web.Areas.Admin.Controllers.ItemController.Index)
}
};
I expect the HTML.ActionLink to return to the viewname set in the setASDraftParams variable
Since you are using dictionary, you need to use the right key to get the value. DictionaryVariable[key]
Try with:
#Html.ActionLink("AQUI", "Index", "Home", new { FromRouteAttribute = setAsDraftParams["returnViewName"] },
new { onclick = "return confirm('Are sure you want to set this Item as a draft?');" })

Passing a dropdown selected value to a contorller

I'm playing around in an MVC application and am trying to figure out something that seems pretty straight forward.
I have a Index.cshtml file in my Views/Home/ folder that is pretty simple (below)
Index view
...
<div>
Search
#Html.DropDownList("selection", MyProject.Util.Lists.GetMyList(), "Select One")
#Html.ActionLink("Search", "Index", "Search", new { st = xxx }, null)
</div>
...
I also have a Search controller that needs to take a "st" value and looks like this
public class SearchController : Controller
{
// GET: Search
public ActionResult Index(string st)
{
ApplicationDbContext db = new ApplicationDbContext();
List<Report> filteredReports = db.Reports.Where(r => r.Tag == st).ToList();
return View(filteredReports);
}
}
What I'm not sure of how do is grab what ever value is selected from the drop down and add that to my Html.ActionLink where I just have 'xxx' now.
Clicking on the link usuallly does a new GET request to the href attribute value of the link. It will not send any data from your form.
You need to use javascript and hijack the click event on the link and append the selected option value from the SELECT element as querystring to that and send it.
So give an id to the link which you can use later to wireup the click event
#Html.ActionLink("Search", "Index", "Search", null, new {#id="search"})
And the javascript
$(function(){
$("#search").click(function(e){
e.preventDefault();
window.location.href=$(this).attr("href")+"?st="+$("#selection").val();
});
});
Another option is to use the form submit. Wrap your select element inside a form and have a submt button which sends the form to the action method. This method does not need javascript. But your select input element name should match with your parameter name.
#using(Html.BeginForm("Index","Search",FormMethod.Get))
{
<div>
Search
#Html.DropDownList("st", MyProject.Util.Lists.GetMyList(), "Select One")
<input type="submit" value="Search" />
</div>
}
If you do not prefer to have button, but need the link element, you can use javascript to submit the form (like we did in the first approach). With this approach you do not need to manually append the querystring.
You have to call a AJAX POST call to your controller which store selected value, and then when your action link event fire get stored value from there.
AJAX:
$.ajax(
{
url:your url,
data:{"st":dropdown selected value},
type:"post"
});
Controller:
public ActionResult Index()
{
string st=TempData["st"].ToString();
ApplicationDbContext db = new ApplicationDbContext();
List<Report> filteredReports = db.Reports.Where(r => r.Tag == st).ToList();
return View(filteredReports);
}
public void SetSt(string st)
{
TempData["st"] = st;
}

Passing route values from a form using FormMethod.Get [duplicate]

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?
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)
Remove "id"
from
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })

chaining the items of Razor DropDownLists

I have 3 DropDownLists; when I select an item in #1, I want the items in #2 to be filled according the value of #1. And when I select an item in #2, the items in #3 should be filled according the selection in #2. They all are located in a form named GetItemsForLeve1. I've started by using onchange of the drop-down.
<% using (Html.BeginForm("GetItemsForLeve1", "Index"))
{ %>
Main Group: <%:Html.DropDownList("Level1", (SelectList)ViewBag.Level1, "Select One", new { onchange = "$this.form.submit()" })%>
<%:Html.DropDownList("Level2", (SelectList)ViewBag.Level2, "-", new { onchange = "$this.form.submit()" })%>
<%:Html.DropDownList("Level3", (SelectList)ViewBag.Level3, "-", new { onchange = "$this.form.submit()" })%>
<input type="submit" value="Filter" />
<%}%>
Is it possible to fill the level 2 and level 3 drop-down lists without sending the page back to the server?
How can I tell which drop-down list has been clicked in the GetItemsForLevel action?
I am completely new to MVC, so I appreciate telling me in a simple way?
Thank you
As far as I know, there's not really a component that does this for you. But you can use the Ajax.BeginForm helper to build it.
the first ajax form should contain the first select list, and post back to an action that returns a partial view
the partial view in 1. should return the second ajax form with a second select list
and so forth
So the main Razor view should contain something like this:
#using (Ajax.BeginForm("SecondAjaxForm", new AjaxOptions() { UpdateTargetId = "secondFormDiv" })
{
#Html.DropDownList("selectList1", Model.FirstSelectList, new { onchange = "this.form.submit()")
}
<!-- the second AJAX form + drop-down list will get populated here
<div id="secondFormDiv"></div>
And the SecondAjaxForm action:
public ActionResult SecondAjaxForm(string selectList1)
{
SelectList secondSelectList;
// populate the second select list here
return PartialView("SecondAjaxForm", secondSelectList);
}
The partial view SecondAjaxForm should be basically the same as the first form above.
#model SelectList
#using (Ajax.BeginForm("ThirdAjaxForm", new AjaxOptions() { UpdateTargetId = "thirdFormDiv" })
{
#Html.DropDownList("selectList2", Model, new { onchange = "this.form.submit()")
}
<!-- the third AJAX form + drop-down list (if any) will get populated here
<div id="thirdFormDiv"></div>

DropDown list onchange event and AJAX in MVC

I have a code block in my MVC view as follows:
<%using (Ajax.BeginForm("MyAction", new { action = "MyAction", controller = "Home", id = ViewData["selected"].ToString() }, new AjaxOptions { UpdateTargetId = "Div1" }))
{ %>
<%=Html.DropDownList("ddl", ViewData["MyList"] as SelectList, new { onchange = "this.form.submit()" })%>
<%} %>
I want to set the value of ViewData["selected"] so that i can send it to the desired action.
Can anyone please suggest how can i do this?
thanks!
Instead of using a form, why not use a jQuery onChange event on your drop down?
$(document).ready(function() {
$("#ddl").change(function() {
var strSelected = "";
$("#ddl option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Home/MyAction/" + strSelected;
$.post(url, function(data) {
// do something if necessary
});
});
});
ViewData is not the place to pass data back to the server side. Values of html input controls within form tag are conveniently available in action method. You can get these values either from various types of action method arguments (model, formcollection etc).
Here is a link to free asp.net mvc ebook tutorial. Is a good resource for asp.net mvc.
Found solution at this post it is just small chnge
Yes, that’s right – only change is replacing:
onchange = “this.form.submit();”
with:
onchange = “$(this.form).submit();”

Resources