Reputation: 65
I have a working solution, but I don't know how to reload the page after a certain ID is selected from the drop down list. My list is being populated from the DB. When I select it, I can see the ID and the corresponding data for it. However, there is no change on the screen.
Controller class:
public ActionResult Index()
{
var model = test.getStuff();
ViewBag.IDs = new SelectList(test.getID(), "", "ID");
return View(model);
}
[HttpPost]
public ActionResult getDataBySelectedID(string selectedId)
{
var que = test.getHello(selectedId);
return View(que);
}
View Class:
@Html.DropDownList("ID", ViewBag.IDs as SelectList)
$(document).ready(function () {
$("#ID").on("change", function () {
var selectedId = this.value;
var url = "/Sample/getDataBySelectedID";
$.ajax({
method: "POST",
dataType: "json",
url: url,
data: {
selectedId: selectedId
}
});
});
});
How would I be able to reload the page with the selected value and its corresponding data?
Any help would be appreciated!
Thank you.
Upvotes: 0
Views: 8082
Reputation: 4222
no need to use ajax in your case
just do a
window.location.href = "/Sample/getDataBySelectedID?selectedId=" +selectedId;
in your onchange function, and in your view return it as
[HttpGet]
public ActionResult getDataBySelectedID(string selectedId)
{
var que = test.getHello(selectedId);
return View("~/Index.cshtml",que);
}
hoping "que" is the same kind of model like you are using on your Index function
Upvotes: 0
Reputation: 24957
Since you want to reload the page after dropdown selection changed, you should handle change
event to redirect with query string like this:
$("#ID").on("change", function () {
var selectedId = $(this).val();
window.location.href = '@Url.Action("getDataBySelectedID", "Sample")' + '?selectedId=' + selectedId;
});
Take note that window.location.href
uses HTTP GET method, hence the target action must use [HttpGet]
instead of [HttpPost]
:
[HttpGet]
public ActionResult getDataBySelectedID(string selectedId)
{
var que = test.getHello(selectedId);
// don't forget to repopulate ViewBag from SelectList here
return View("Index", que); // return same page with different model contents
}
Make sure getHello()
method return type is the same as getStuff()
method to avoid passed model item related exceptions.
But if you want to submit the form and show it again afterwards, then use $('form').submit()
instead:
jQuery
$("#ID").on("change", function () {
$('form').submit();
});
Controller
[HttpPost]
public ActionResult getDataBySelectedID(ViewModel model)
{
// do something
return View(model);
}
Upvotes: 1
Reputation: 564
in getDataBySelectedID return view similar to Index that is construct model with filter applied and return View(model)
Upvotes: 1