查看
@model BinViewModel
<form id="binForm">
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<fieldset>
<div class="form-group">
@Html.LabelFor(model => model.CreateBinModel.StreetName, htmlAttributes: new { @class = "col-form-label" })
@Html.TextBoxFor(model => model.CreateBinModel.StreetName, new { @class = "form-control", @placeholder = "Street Name", @autocomplete = "off" })
@Html.ValidationMessageFor(model => model.CreateBinModel.StreetName, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.CreateBinModel.Capacity, htmlAttributes: new { @class = "col-form-label" })
@Html.TextBoxFor(model => model.CreateBinModel.Capacity, new { @class = "form-control", @placeholder = "Capacity", @autocomplete = "off" })
@Html.ValidationMessageFor(model => model.CreateBinModel.Capacity, "", new { @class = "text-danger" })
</div>
<br />
<button type="submit" id="btnCreateBin" class="btn btn-success">
<span class="fa fa-arrow-right fa-fw"></span> Create Bin
</button>
</fieldset>
</form>
型号
public class CreateBin
{
public string? StreetName { get; set; }
public string? Capacity { get; set; }
}
public class BinViewModel
{
public CreateBin CreateBinModel { get; set; }
public List<Bin> Bins { get; set; }
}
Bin.js
$(document).ready(function () {
$('#binForm').on('submit', function (e) {
e.preventDefault();
console.log($(this).serialize());
$.ajax({
url: '/Bin/Create', // Your action URL
type: 'POST',
data: $(this).serialize(),
success: function (response) {
if (response.success) {
$('#createBinModal').modal('hide');
$('#successModal .modal-body p').text(response.message);
$('#successModal').modal('show');
} else {
// Display error modal with the error message
$('#createBinModal').modal('hide');
$('#errorModal .modal-body p').text(response.message);
$('#errorModal').modal('show');
}
}
});
});
});
图片:
我尝试添加 bin,然后模型的值为空,然后我在控制台日志中检查了一些内容。在附图中我当前遇到了问题。无法正确地将表单的值传递给模型。
任何人都可以帮助代码中的错误是什么。
谢谢你
发送的请求负载与
CreateBinModel
结构不匹配,因为使用“CreateBinModel”前缀发送的属性。
您应该使用
Name
属性来覆盖原始生成的 name
属性
@Html.TextBoxFor(model => model.CreateBinModel.StreetName
, new { Name = "StreetName", @class = "form-control", @placeholder = "Street Name", @autocomplete = "off" })
@Html.TextBoxFor(model => model.CreateBinModel.Capacity
, new { Name = "Capacity", @class = "form-control", @placeholder = "Capacity", @autocomplete = "off" })