首页 > 解决方案 > 为什么当我想添加新客户时我的客户 ID 始终为空

问题描述

当我想将新客户添加到我的数据库中时,我将返回到同一页面并且客户没有添加到数据库中。

一切都很好,直到我将验证添加到我的客户控制器中。

添加后

if (!ModelState.IsValid)
{
    var viewModel = new NewCustomerViewModel
            {
                Customer = customer,
                MemberShipTypes = _context.MemberShipTypes.ToList()
            };

    return View("New", viewModel);
}

客户类

public class Customer
{
    public int? Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    public bool IsSubscribedToNewsLetter { get; set; }

    public MemberShipType MemberShipType { get; set; }

    [Display(Name = "Membership Type")]
    public int MemberShipTypeId { get; set; }

    [Display(Name = "Birth of Date")]
    [Min18YearsIfAMember]
    public  DateTime? BirthDate { get; set; }
}

我遇到了这个问题:

New看法

@using System.Security.Cryptography
@model Vidly.VIewModels.NewCustomerViewModel
@{
    ViewBag.Title = "New";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{
    if (Model.Customer != null)
    {
        <h2>Edit Customer</h2>
    }
    else
    {
        <h2>New Customer</h2>
    }
}

@using (Html.BeginForm("Save", "Customers"))
{
  @Html.HiddenFor(m => m.Customer.Id)

    <div class="form-group">
        @Html.LabelFor(m => m.Customer.Name)
        @Html.TextBoxFor(m => m.Customer.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Customer.Name)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Customer.BirthDate)
        @Html.TextBoxFor(m => m.Customer.BirthDate, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Customer.BirthDate)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Customer.MemberShipTypeId)
        @Html.DropDownListFor(m => m.Customer.MemberShipTypeId, new SelectList(Model.MemberShipTypes,"Id","Name"), "", new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Customer.MemberShipTypeId)
    </div>

    <div class="checkbox">
        <label>
            @Html.CheckBoxFor(m => m.Customer.IsSubscribedToNewsLetter) Subscribed to NewsLetter?
        </label>
    </div>
  

    <button type="submit" class="btn btn-primary">Save</button>
}

CustomerController

public class CustomersController : Controller
{
    private ApplicationDbContext _context;

    public CustomersController()
    {
        _context = new ApplicationDbContext();
    }

    protected override void Dispose(bool disposing)
    {
        _context.Dispose();
    }

    [HttpPost]
    public ActionResult Save(Customer customer)
    {
        if (!ModelState.IsValid)
        {
            var viewModel = new NewCustomerViewModel
            {
                Customer = customer,
                MemberShipTypes = _context.MemberShipTypes.ToList()
            };

            return View("New", viewModel);
        }

        if (customer.Id == 0)
            _context.Customers.Add(customer);
        else
        {
            var customerInDb = _context.Customers.Single(c => c.Id == customer.Id);

            customerInDb.Name = customer.Name;
            customerInDb.BirthDate = customer.BirthDate;
            customerInDb.MemberShipTypeId = customer.MemberShipTypeId;
            customerInDb.IsSubscribedToNewsLetter = customer.IsSubscribedToNewsLetter;
        }

        _context.SaveChanges();

        return RedirectToAction("Index", "Customers");
    }

    public ActionResult New()
    {
        var memberships = _context.MemberShipTypes.ToList();

        var viewModel = new NewCustomerViewModel
        {
            MemberShipTypes = memberships
        };

        return View(viewModel);
    }

    // GET: Customer
    public ActionResult Index()
    {
        var customers = _context.Customers.Include(c=> c.MemberShipType).ToList();

        return View(customers);
    }

    public ActionResult Details(int id)
    {
        var customer = _context.Customers.Include(c => c.MemberShipType).SingleOrDefault(c => c.Id == id);

        if (customer == null)
            return HttpNotFound();

        return View(customer);
    }

    public ActionResult Edit(int id)
    {
        var customer = _context.Customers.SingleOrDefault(c => c.Id == id);

        if (customer == null)
            return HttpNotFound();

        var viewModel = new NewCustomerViewModel
        {
            Customer = customer,
            MemberShipTypes = _context.MemberShipTypes.ToList()
        };

        return View("New", viewModel);
    }
}

[Min18YearsIfAMember]如果是新成员,是我对至少 18 岁的自定义验证。

标签: c#asp.net-mvcdatabaseentity-framework

解决方案


因为您的客户 ID 可以为空修复您的代码

 if (customer.Id == null || customer.Id == 0 )

或者您可以更改您的 Id 属性

  public int Id { get; set; }

推荐阅读