I am developing web app with asp.net core 3.1.
I have an ajax call sends a ConsultViewModel object to my controller, but in controller it is getting null. I don't understand my error. I changed the ajax "data: JSON.stringify({consultView: consultView})" to "data: JSON.stringify(consultView)" but error persist.
How do i solve this problem?
My code is just as follow:
ViewModel
public class ConsultViewModel
{
public int Id { get; set; }
[Range(1, int.MaxValue, ErrorMessage = "Select a Department")]
public int DepartmentId { get; set; }
[Required]
public string Description { get; set; }
public string Date { get; set; }
public IEnumerable<SelectListItem> Department { get; set; }
}
View
@model MyApp.AppWeb.Models.ConsultViewModel;
<h1>Edit</h1>
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="DepartmentId" class="control-label"></label>
<select asp-for="DepartmentId" asp-items="Model.Department" class="form-control"></select>
<span asp-validation-for="DepartmentId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Dateate" class="control-label"></label>
<input asp-for="Date" class="form-control" disabled />
<span asp-validation-for="Date" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" class="form-control" cols="40" rows="5"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div id="@Model.Id" class="form-group">
<input type="button" class="btn btn-primary" value="Save" id="btnEdit"/>
</div>
</form>
Scripts
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function () {
$('#btnEdit').click(function () {
var id = $(this).parent()[0].id;
var consultView = {
Id: id,
DepartmentId: $('#DepartmentId').val(),
Date: $('#Date').val(),
Description: $('#Description').val()
};
$.ajax({
type: 'POST',
url: "@Url.Action("Editar")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({consultView: consultView}),
success: function (data) {
alert(data.message);
},
error: function (ex) {
alert('Error.' + ex);
}
});
});
});
</script>
}
[HttpPost]
//[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ConsultViewModel consultView)
{
if (ModelState.IsValid)
{
//More code..
return Json(new { success = true, message = "Done." });
}
return View(consultaView);
}
Thank!
question from:
https://stackoverflow.com/questions/65947841/passing-value-from-mvc-view-to-controller-using-ajax 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…