C# asp.net mvc core 2选择值在视图模型中始终为0

C# asp.net mvc core 2选择值在视图模型中始终为0,c#,asp.net-core,asp.net-core-mvc,asp.net-core-2.0,C#,Asp.net Core,Asp.net Core Mvc,Asp.net Core 2.0,我在视图中有一个select,它总是将0返回到我的视图模型,我不知道为什么: 查看模型: // CreateLifeInsuranceViewModel.cs using InsuranceListManager.Models.EntityFrameworkModels; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace InsuranceListManager.Mo

我在视图中有一个select,它总是将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; }
    }
}
@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");}
}
//CreateLifeInsuranceViewModel.cs
使用InsuranceListManager.Models.EntityFrameworkModels;
使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations;
命名空间InsuranceListManager.Models.ViewModels.Home
{
公共类CreateLifeInsuranceViewModel
{
[必需]
公共int客户ID;
公共IList客户{get;set;}
[必需]
公共字符串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);
    }
}
公共类HomeController
{
公共IActionResult CreateLifeInsurance()
{
var客户=(
从数据库中的c中,客户选择c
).ToList();
var模型=新建CreateLifeInsuranceViewModel
{
顾客=顾客
};
返回视图(模型);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务CreateLifeInsurance(CreateLifeInsuranceViewModel模型)
{
if(ModelState.IsValid)
{
var category=\u db.InsuranceCategories.Where(c=>c.Id==InsuranceCategoryModel.LIFE\u INSURANCE).First();
var保险=新的保险模式
{
CategoryId=category.Id,
CustomerId=model.CustomerId
};
_db.Add(保险);
等待_db.SaveChangesAsync();
var人寿保险=新的人寿保险模型
{
InsuranceId=insurance.Id,
InsuredPersonCPF=型号。InsuredPersonCPF
};
_db.Add(人寿保险);
等待_db.SaveChangesAsync();
返回重定向到操作(名称(索引));
}
返回请求(ModelState);
}
}
查看:

// 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; }
    }
}
@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");}
}
@model InsuranceListManager.Models.ViewModels.Home.CreateLifeInsuranceViewModel
@{
ViewData[“标题”]=“新保险”;
}
新保险

顾客 选择客户 被保险人中央公积金

但由于某些原因,我从视图模型中的此选择中收到的值始终为零:

另外,如果我没有从select中选择任何项目,asp验证将无法捕获

在过去的4个小时里,我一直在研究这个问题,没有发现任何类似的问题


我使用的是Asp.Net MVC Core 2、.Net Core SDK 2.2、Windows 10 Pro和Visual Studio 2017社区版。

您看到的值是
0
,因为这是
int
的默认值

提交表单时,默认模型绑定器将尝试读取表单数据,并将值分配给视图模型对象的相应属性。如果
CustomerId
属性且属性是集合表格,则Model binder将能够成功地执行此操作

在共享的代码中,您不是在创建属性,而是在创建字段。因此,模型绑定器无法为此设置值

要解决此问题,请通过指定
set
get
属性访问器,将
CustomerId
属性更改为set

[Required]
public int CustomerId { set; get; }

在我的例子中,问题是我忘记了编辑绑定属性(ref:),当我跟踪我的控制器时,它就留在那里了

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Name,BenchmarkScore,PicturePath,Price")] PcComponentItemVM componentVM)
    }
    {
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务编辑(int-id,[Bind(“id,Name,BenchmarkScore,PicturePath,Price”)]PcComponentItemVM-componentVM)
}
{

这不完全是关于“属性可设置”,而是当他使用字段时,它需要是一个属性。你没有错,只是terminologyIt必须是一个带有
set
property accessor的属性,以便model binder设置值。
public int CustomerId{get;}
即使是属性也不起作用。同意。当然值得一提的是,属性也需要设置。我刚才提到,我们不能将他的
CustomerId
字段称为“未设置的属性”。