0

我对 ASP MVC 完全陌生,如果我问一些愚蠢的问题,我很抱歉。

ModelState 不会得到验证。它说venue.VenueType.Type是空的。我这样做对吗?我已经Type在控制器中给出了一个值(不知道这是否是最佳实践),但 ModelState 无法识别这一点。

我读过关于使用TryUpdateModel. 这并没有带来任何成功,尽管我不确定我是否正确使用它。

我应该为此使用 ViewModel 吗?我在其中使用哪些字段?

这是两个模型:

public class Venue
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public virtual VenueType VenueType { get; set; }
    public virtual ICollection<VisitInfo> VisitInfos { get; set; }
}

public class VenueType
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Type { get; set; }
}

Venue 类的创建操作:

    //
    // GET: /Venue/Create

    public ActionResult Create()
    {
        ViewBag.venueTypes = new SelectList(context.VenueTypes, "Id", "Type");
        return View();
    } 

    //
    // POST: /Venue/Create

    [HttpPost]
    public ActionResult Create(Venue venue)
    {
        venue.VenueType = context.VenueTypes.Find(venue.VenueType.Id);

        ViewBag.venueTypes = new SelectList(context.VenueTypes, "Id", "Type");

        if (ModelState.IsValid)
        {
            context.Venues.Add(venue);
            context.SaveChanges();
            return RedirectToAction("Index");  
        }
        return View(venue);
    }

和一个创建视图:

@model eBouncer_Web.Models.Venue

@* This partial view defines form fields that will appear when creating and editing entities *@
<div class="editor-label">
    @Html.LabelFor(model => model.VenueType)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.VenueType.Id, (SelectList) ViewBag.venueTypes)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>
4

1 回答 1

1

如果您编写自己的验证,则不需要ModelState.

 [HttpPost]
    public ActionResult Create(Venue venue)
    {
        venue.VenueType = context.VenueTypes.Find(venue.VenueType.Id);

        ViewBag.venueTypes = new SelectList(context.VenueTypes, "Id", "Type");

        if (Venue != null && Venue.Name != null)//etc.. or other validations get here...
        {
            context.Venues.Add(venue);
            context.SaveChanges();
            return RedirectToAction("Index");  
        }
        return View(venue);
    }
于 2013-07-29T15:59:26.887 回答