Reputation: 1925
I have a model as follows:
public class SearchModel
{
public List<CheckBoxResponse> Status { get; set; }
}
public class CheckBoxResponse
{
public string ItemText { get; set; }
public bool Selected { get; set; }
}
The view is as follows:
<div id="divSearchParams">
<div class="col-xs-12 col-sm-12 col-md-5 col-lg-5">
<div class="form-group">
<label>Status</label> <br />
@for (var i = 0; i < Model.Status.Count; i++)
{
<input type="checkbox" asp-for="@Model.Status[i].Selected" />
<label asp-for="@Model.Status[i].Selected">@Model.Status[i].ItemText</label>
<input type="hidden" asp-for="@Model.Status[i].ItemText" />
}
</div>
</div>
</div>
My AJAX call :
$(document).on("click", "#search", function () {
var model = $('#divSearchParams').find("input,select,textarea").serialize();
$.ajax({
url: targetUrl,
type: 'POST',
data: { model: model },
cache: true,
async: true,
}).done(function (result) {
}).fail(function (error) {
}).always(function () {
}
});
});
So on serialise, the model value is "Status%5B0%5D.ItemText=Open&Status%5B1%5D.Selected=true"
However when I check the value of model in controller, I see Status value inside model is null.
public async Task<ActionResult> Students(SearchModel model)
{
}
What am I missing?
Upvotes: 2
Views: 110
Reputation: 36645
Ajax post data with contentType application/x-www-form-urlencoded; charset=UTF-8
by default, you need change:
data: { model: model },
To:
data: model,
Be sure your backend controller is not ApiController, otherwise you need specific [FromForm]
attribute on SearchModel
parameter.
public class HomeController : Controller
{
[HttpPost]
public async Task<ActionResult> Students(SearchModel model)
{
//do your stuff...
}
}
Result display:
Reference:
https://stackoverflow.com/a/65572281/11398810
Update:
If your action contains a second string parameter:
[HttpPost]
public async Task<ActionResult> Students(SearchModel model,string Id)
{
//....
}
Add an input which has name="Id"
in the View:
<input name="Id" />
If your action contains a second model type parameter:
Model:
public class TestViewModel
{
public int Id{ get; set; }
}
Controller:
[HttpPost]
public async Task<ActionResult> Students(SearchModel model, TestViewModel Item)
{
//...
}
Add an input which has name="Item.Id"
in the View:
<input name="Item.Id" />
Update2:
Controller:
[HttpPost]
public async Task<ActionResult> Students(SearchModel model, string Id,bool isPartial)
{
return View();
}
View:
$(document).on("click", "#search", function () {
var id = "aaa";
var isPartial = false;
var model = $('#divSearchParams').find("input,select,textarea").serialize();
$.ajax({
url: "/Home/Students?Id=" + id + "&isPartial=" + isPartial,
type: 'POST',
data: model,
cache: true,
async: true,
}).done(function (result) {
}).fail(function (error) {
}).always(function () {
});
});
Upvotes: 2