How can I keep selected values for both dropdown after submit action?
In my scenarios, my cascaded dropdown is populating from partial view. I'm new to ASP.NET Core MVC. Let me know if you want more clarifications.
My view:
<form asp-controller="Recommendation" asp-action="SubmitData" method="post">
<select id="States" class="form-control selectpicker" asp-for="StateID" asp-
items="@(new SelectList(ViewBag.StateList,"StateID","State"))"
placeholder="Select Categories"
onchange="console.log($(this).children(':selected').length)">
</select>
@Html.DropDownListFor(m => m.CityID, new SelectList(""), new {@class="select2
form-control", @style = "width: 100%" })
<button id="btnSubmit" class="btn btn-secondary btn-sm">Submit</button>
</form>
onChange
function on first dropdown to call 2nd one:
<script type="text/javascript">
$(document).ready(function () {
$("#States").change(function () {
var StateID = $(this).val();
/*debugger;*/
$("#CityID").empty();
$.ajax({
type: "Get",
url: "/Recommendation/GetCityList?iStateID=" + StateID,
contentType: "html",
success: function (response) {
$("#CityID").append(response);
},
error: function (jqXHR, textStatus, errorThrown) {
}
})
})
});
</script>
Partial View for Child dropdown
<option value="">Select City</option>
@if (ViewBag.CityOptions != null)
{
foreach(var item in ViewBag.CityOptions)
{
<option value="@item.Value">@item.Text</option>
}
}
Controller:
[HttpGet]
public ActionResult IndexGet()
{ // From where I get values.
Entity entity = new Entity();
StateList = gateway.SelectList();
StateList.Insert(0, new Model { StateID = 0, State = "Select State" });
ViewBag.StateList = StateList;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SubmitData(RecommendModel recommendModel)
{ // Submit form method and I used RedirectToAction for calling view again.
{
}
return RedirectToAction("IndexGet", "Recommendation");
}
[HttpGet]
public ActionResult GetCityList(long iStateID)
{ // For partial call
Entity entity = new Entity();
MCAlist = entity.GetCityList(iStateID);
ViewBag.CityOptions = new SelectList(MCAlist,"MCAID","MCA");
return PartialView("_CityOptionPartial");
}
You can send same model again in post action.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult IndexGet(RecommendModel recommendModel)
{
return View(model);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.