asp.net mvc core 2 select 视图模型中的值始终为 0
asp.net mvc core 2 select value is always 0 in view model
我的视图模型中有一个 select 总是 returns 0,我不知道为什么:
查看模型:
// CreateLifeInsuranceViewModel.cs
using InsuranceListManager.Models.EntityFrameworkModels;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace InsuranceListManager.Models.ViewModels.Home
{
public class CreateLifeInsuranceViewModel
{
[Required]
public int CustomerId;
public IList<CustomerModel> Customers { get; set; }
[Required]
public string InsuredPersonCPF { get; set; }
}
}
控制器
public class HomeController
{
public IActionResult CreateLifeInsurance()
{
var customers = (
from c in _db.Customers select c
).ToList();
var model = new CreateLifeInsuranceViewModel
{
Customers = customers
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateLifeInsurance(CreateLifeInsuranceViewModel model)
{
if (ModelState.IsValid)
{
var category = _db.InsuranceCategories.Where(c => c.Id == InsuranceCategoryModel.LIFE_INSURANCE).First();
var insurance = new InsuranceModel
{
CategoryId = category.Id,
CustomerId = model.CustomerId
};
_db.Add(insurance);
await _db.SaveChangesAsync();
var lifeInsurance = new LifeModel
{
InsuranceId = insurance.Id,
InsuredPersonCPF = model.InsuredPersonCPF
};
_db.Add(lifeInsurance);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return BadRequest(ModelState);
}
}
查看:
@model InsuranceListManager.Models.ViewModels.Home.CreateLifeInsuranceViewModel
@{
ViewData["Title"] = "New Insurance";
}
<h1>New Insurance</h1>
<hr />
<form asp-action="CreateLifeInsurance">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-row">
<div class="form-group col-sm-6">
<label asp-for="CustomerId">Customer</label>
<select class="form-control" asp-for="CustomerId" asp-items="@(new SelectList(Model.Customers, "Id", "Name"))">
<option value="">Select the customer</option>
</select>
<span asp-validation-for="CustomerId" class="text-danger"></span>
</div>
<div class="form-group col-sm-6">
<label asp-for="InsuredPersonCPF">Insured Person CPF</label>
<input type="text" class="form-control" asp-for="InsuredPersonCPF" placeholder="CPF" />
<span asp-validation-for="InsuredPersonCPF" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
<a class="btn" asp-action="Index">Cancel</a>
</div>
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
在呈现的 HTML 中,select 具有正确的值,如您在屏幕截图中所见:
但由于某种原因,我从视图模型中的 select 收到的值始终为零:
此外,如果我不 select select 中的任何项目,asp 验证将无法捕获。
过去 4 小时我一直在研究这个问题,没有发现任何类似的问题。
我正在使用 Asp.Net MVC Core 2、.Net Core SDK 2.2、Windows 10 Pro 和 Visual Studio 2017 Community Edition。
您看到的是值 0
,因为这是 int
的默认值。
提交表单时,默认模型绑定器将尝试读取表单数据并将值分配给视图模型对象的相应属性。如果 CustomerId
是 属性 并且 属性 是 set[=29=,则模型绑定器将能够成功执行此操作]table.
在您共享的代码中,您创建的不是 属性 而是一个字段。因此模型活页夹无法为此设置值。
要解决此问题,请将 CustomerId
属性 更改为 settable,方法是指定 set
和 get
属性 访问器。
[Required]
public int CustomerId { set; get; }
我的问题是我忘记编辑 Bind 属性(参考:https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.bindattribute?view=aspnet-mvc-5.2),当我搭建我的控制器时,它留在了那里。
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,BenchmarkScore,PicturePath,Price")] PcComponentItemVM componentVM)
}
{
我的视图模型中有一个 select 总是 returns 0,我不知道为什么:
查看模型:
// CreateLifeInsuranceViewModel.cs
using InsuranceListManager.Models.EntityFrameworkModels;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace InsuranceListManager.Models.ViewModels.Home
{
public class CreateLifeInsuranceViewModel
{
[Required]
public int CustomerId;
public IList<CustomerModel> Customers { get; set; }
[Required]
public string InsuredPersonCPF { get; set; }
}
}
控制器
public class HomeController
{
public IActionResult CreateLifeInsurance()
{
var customers = (
from c in _db.Customers select c
).ToList();
var model = new CreateLifeInsuranceViewModel
{
Customers = customers
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateLifeInsurance(CreateLifeInsuranceViewModel model)
{
if (ModelState.IsValid)
{
var category = _db.InsuranceCategories.Where(c => c.Id == InsuranceCategoryModel.LIFE_INSURANCE).First();
var insurance = new InsuranceModel
{
CategoryId = category.Id,
CustomerId = model.CustomerId
};
_db.Add(insurance);
await _db.SaveChangesAsync();
var lifeInsurance = new LifeModel
{
InsuranceId = insurance.Id,
InsuredPersonCPF = model.InsuredPersonCPF
};
_db.Add(lifeInsurance);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return BadRequest(ModelState);
}
}
查看:
@model InsuranceListManager.Models.ViewModels.Home.CreateLifeInsuranceViewModel
@{
ViewData["Title"] = "New Insurance";
}
<h1>New Insurance</h1>
<hr />
<form asp-action="CreateLifeInsurance">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-row">
<div class="form-group col-sm-6">
<label asp-for="CustomerId">Customer</label>
<select class="form-control" asp-for="CustomerId" asp-items="@(new SelectList(Model.Customers, "Id", "Name"))">
<option value="">Select the customer</option>
</select>
<span asp-validation-for="CustomerId" class="text-danger"></span>
</div>
<div class="form-group col-sm-6">
<label asp-for="InsuredPersonCPF">Insured Person CPF</label>
<input type="text" class="form-control" asp-for="InsuredPersonCPF" placeholder="CPF" />
<span asp-validation-for="InsuredPersonCPF" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
<a class="btn" asp-action="Index">Cancel</a>
</div>
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
在呈现的 HTML 中,select 具有正确的值,如您在屏幕截图中所见:
但由于某种原因,我从视图模型中的 select 收到的值始终为零:
此外,如果我不 select select 中的任何项目,asp 验证将无法捕获。
过去 4 小时我一直在研究这个问题,没有发现任何类似的问题。
我正在使用 Asp.Net MVC Core 2、.Net Core SDK 2.2、Windows 10 Pro 和 Visual Studio 2017 Community Edition。
您看到的是值 0
,因为这是 int
的默认值。
提交表单时,默认模型绑定器将尝试读取表单数据并将值分配给视图模型对象的相应属性。如果 CustomerId
是 属性 并且 属性 是 set[=29=,则模型绑定器将能够成功执行此操作]table.
在您共享的代码中,您创建的不是 属性 而是一个字段。因此模型活页夹无法为此设置值。
要解决此问题,请将 CustomerId
属性 更改为 settable,方法是指定 set
和 get
属性 访问器。
[Required]
public int CustomerId { set; get; }
我的问题是我忘记编辑 Bind 属性(参考:https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.bindattribute?view=aspnet-mvc-5.2),当我搭建我的控制器时,它留在了那里。
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,BenchmarkScore,PicturePath,Price")] PcComponentItemVM componentVM)
}
{