Reputation: 2301
I have a dropdown list in a View. And if I change the selection, I want to change immediately the values in the View. The textbox of Type and Description. How do you do that?
@Model GenreModel
@using (Html.BeginForm("EditGenre", "Home", FormMethod.Post))
{
@model GenreModel
<div class="text-center">
<h1 class="display-4">Edit genre</h1>
<p> <input type="submit" value="submit" name="Save" /></p>
<p>
<label>Select genre: </label>
@Html.DropDownListFor(Model => Model.Description, new SelectList(ViewBag.GenreList, "Description", "Description"), new { onchange = "onChangeSelection(this.value);" });
</p>
<p>
<label>Type</label>@Html.TextBoxFor(Model => Model.Type)
</p>
<p>
<label>Description</label>@Html.TextBoxFor(Model => Model.Description)
</p>
</div>
}
This is the method in the Controller.
[HttpPost]
public IActionResult EditGenre(string description)
{
var dto = _genreService.GetGenreByName(description);
var model = _mapper.Map<GenreDto, GenreModel>(dto);
ViewBag.GenreList = _genreService.GetAllGenres().OrderBy(g => g.Description);
return View(model);
}
and finally:
<script>
function onChangeSelection(val) {
{
$.ajax({
url: @Url.Action("EditGenre", "Home"),
//type: "POST",
data: { description: val },
success: function (data) {
// put result of action into element with class "result"
$('.result').html(data);
},
error: function () {
alert(val + ' not found.');
}});
}
</script>
Upvotes: 0
Views: 453
Reputation: 2301
It seems my DropDownList didn't fire a Submit. I leave the javascript and using a hidden field. And this solution works fine.
<p>
<label>Select genre: </label>
@Html.Hidden("#Discription")
@Html.DropDownListFor(Model => Model.Description, new SelectList(ViewBag.GenreList, "Description", "Description"), new { onchange = "this.form.submit();" });
</p>
Upvotes: 0
Reputation: 8469
Change the DropDownList like this:
@Html.DropDownListFor(Model => Model.Description, new SelectList(ViewBag.GenreList, "Description", "Description"));
And submit the form in the onchange function:
<script>
$("#Description").on("change", function () {
$(this).closest("form").submit();
})
</script>
Upvotes: 1