I'm completely new to C# and ASP.NET MVC.
In my current project, which uses ASP.NET Core 8, I'm facing issues with updating a section of the form controls.
I've researched this issue and found that most people use partial views and Ajax to update parts of a page (not parts of the form).
I'm attempting to do the same, but I'm encountering problems with model binding after the form is updated via Ajax.
How can I resolve this issue? Thank you!
Model
public class myModel
{
// group ID is for drop down list value.
// update the form if it's changed.
public string groupID {get; set;}
public _myPartialViewModel People {get; set;}
}
Partial view model:
public class _myPartialViewModel
{
public List<Person> peopleList {get; set;}
}
Person class
public class Person
{
public string ID {get; set;}
public string Name {get; set;}
public bool isChecked {get; set;}
}
Method for returning partial view:
public IActionResult UpdateForm(string groupID)
{
List<Person> people = getDataFromDB(groupID);
_myPartailViewModel vm = new _myPartailViewModel(people);
return PartialView("_myPartailView", vm);
}
View
@using myModel
<form asp-action="myAction" asp-controller="myController" method="post">
<div>
@Html.LabelFor(m=>m.groupID)
@Html.DropDownList("DropDownListForGroupID")
</div>
</div id="divToUpdated">
<partial name="_myPartialView", for="People">
</div>
<button type=submit>submit</button>
</form>
Partial View
@using _myPartialViewModel
@for (int i = 0; i < Model.peopleList.count; i++)
{
<div>
@Html.LabelFor(m => m.peopleList[i].Name)
@Html.CheckBoxFor(m => m.peopleList[i].isChecked)
</div>
}
Ajax
$("#DropDownListForGroupID").on("change", function() {
var data = $(this).val();
$.ajax({
type: "POST",
url: "/myController/UpdateForm",
data: {
groupID: data
},
success: function (data) {
$("#divToUpdated").html(data)
},
error: function (errMsg) {
// do something
}})
});
});
The post might be a bit lengthy, thank you for your patience!
I test your code, and make some change like below :
View : remove
<partial name="_myPartialView", for="People">because we use :$("#divToUpdated").html(data)to show partialViewand I get the result like: