在post action方法中获取Null模型

时间:2016-08-25 06:45:03

标签: c# asp.net-core-mvc

我正在使用.NET Core MVC。我的问题是,在我的创建页面成功插入数据后,我一直在获取空模型。

  1. NullReferenceException:对象引用未设置为Index.cshtml中的object.MoveNext实例
  2. @foreach(模型中的酒厂酿酒厂)
  3. ThrowForNonSuccess
  4. HandleNonSuccessAndDebuggerNotification MoveNext
  5. 请告知。

    这是我的显示页面:

    @model IEnumerable<Winery>
    
    @{ 
        ViewData["Title"] = "Wineries";
    }
    
    <h2>Wineries overview</h2>
    
    <p>
        <a asp-action="Create">Create new</a>
    </p>
    
    <table class="table">
        <tr>
            <th>@Html.DisplayNameFor(Model => Model.Name)</th>
            <th>@Html.DisplayNameFor(Model => Model.Country)</th>
        </tr>
    
        @foreach (Winery winery in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(Model => winery.Name)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayFor(Model => winery.Country)
                </td>
            </tr>
        }
       
    </table>

    这是我的模特:

    public class Winery
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [StringLength(30)]
        public string Name { get; set; }
        public Country Country { get; set; }
        public virtual ICollection<Wine> Wines { get; set; }
    }
    
    public enum Country
    {
        France, Germany, Italy, India, Other
    }
    

    这是控制器:

    public class WineriesController : Controller
    {
        private ApplicationDbContext _context;
    
        public WineriesController(ApplicationDbContext context)
        {
            _context = context;
        }
    
        public IActionResult Index()
        {
            List<Winery> wineries = _context.Winery.ToList();
            return View();
        }
    
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }
    
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Winery viewModel)
        {
            if(ModelState.IsValid)
            {
                _context.Winery.Add(viewModel);
                _context.SaveChanges();
    
                return RedirectToAction("Index");
            }
    
            return View(viewModel);
        }
    }
    

0 个答案:

没有答案