在ASP MVC4中更新ModelState

时间:2013-07-29 15:18:37

标签: asp.net-mvc-4 modelstate

我对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>

1 个答案:

答案 0 :(得分: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);
    }