【发布时间】:2016-08-16 22:25:50
【问题描述】:
我目前一直从事 Pluralsight 的 MVC 课程练习。我得到了这个嵌套了 4 个元素的 DropDownList,但无法选择一个并在视图中看到它实际被选中。
@model GigHub.ViewModels.GigFormViewModel
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Gigs"))
{
<p class="alert alert-info">All fields are <strong>required</strong></p>
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(m => m.Venue)
@Html.TextBoxFor(m => m.Venue, new { @class = "form-control", autofocus = "autofocus" })
@Html.ValidationMessageFor(m => m.Venue)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Date)
@Html.TextBoxFor(m => m.Date, new { @class = "form-control", placeholder = "15 Aug 1995" })
@Html.ValidationMessageFor(m => m.Date)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Time)
@Html.TextBoxFor(m => m.Time, new { @class = "form-control", placeholder = "20:30" })
@Html.ValidationMessageFor(m => m.Time)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Genre)
@Html.DropDownListFor(m => m.Genre, new SelectList(Model.Genres, "Id", "Name"), new {@class = "form-control"})
</div>
<button type="submit" value="Save" class="btn btn-success">Save</button>
}
@section scripts
{
@Scripts.Render("~/bundles/jqueryval")
}
我尝试尝试从传递的参数中删除“表单控制”类,然后,实际上可以选择流派,但即使在此之后,提交后,ModelState 总是为 false。
控制器:
using GigHub.Models;
using GigHub.ViewModels;
using Microsoft.AspNet.Identity;
using System.Linq;
using System.Web.Mvc;
namespace GigHub.Controllers
{
public class GigsController : Controller
{
private ApplicationDbContext _context;
public GigsController()
{
_context = new ApplicationDbContext();
}
// GET: Gigs
[Authorize]
public ActionResult Create()
{
var viewModel = new GigFormViewModel
{
Genres = _context.Genres.ToList()
};
return View(viewModel);
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(GigFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
return View("Create", viewModel);
}
var gig = new Gig
{
ArtistId = User.Identity.GetUserId(),
DateTime = viewModel.GetDateTime(),
GenreId = viewModel.Genre,
Venue = viewModel.Venue
};
_context.Gigs.Add(gig);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
}
视图模型:
using GigHub.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace GigHub.ViewModels
{
public class GigFormViewModel
{
[Required]
public string Venue { get; set; }
[Required]
[FutureDate]
public string Date { get; set; }
[Required]
[ValidTime]
public string Time { get; set; }
[Required]
public int Genre { get; set; }
[Required]
public IEnumerable<Genre> Genres { get; set; }
public DateTime GetDateTime() => DateTime.Parse($"{Date}{Time}");
}
}
我花了几个小时在上面,但我已经没有想法了。
【问题讨论】:
-
从
IEnumerable<Genre> Genres中删除[Required] -
Stephen Muecke 明白了。您没有发回您的流派集合,因此您的模型状态永远不会有效。
标签: c# asp.net-mvc razor asp.net-mvc-5