为什么我的ModelState.IsValid在Asp.Net MVC4中没有返回true?

时间:2012-09-30 16:02:51

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

我有一个看起来像的控制器;

[HttpPost]
[Authorize(Roles = "Admin")]
public ActionResult ProjectAdd(PortfolioViewModel model, int[] categories, HttpPostedFileBase thumbnail, HttpPostedFileBase image)
{
    model.ProjectImage = System.IO.Path.GetFileName(image.FileName);
    model.ProjectThubmnail = System.IO.Path.GetFileName(thumbnail.FileName);
    using (PortfolioManager pm = new PortfolioManager())
    {
        using (CategoryManager cm = new CategoryManager())
        {
            if (ModelState.IsValid)
            {
                bool status = pm.AddNewProject(model, categories);
            }
            ViewBag.Categories = cm.GetAllCategories();
            ViewBag.ProjectsList = pm.GetAllProjects();
        }
    }
    return View(model);
}

我的观点是;

@using (Html.BeginForm("projectAdd", "home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Add New Project</legend>

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

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

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

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

        <div class="editor-label">
            <label for="thumbnail">Thumbnail</label>
        </div>
        <div class="editor-field">
            <input type="file" name="thumbnail" id="thumbnail" /> 
        </div>
        <div class="editor-label">
            <label for="image">Image</label>
        </div>
        <div class="editor-field">
            <input type="file" name="image" id="image" /> 
        </div>
        <div class="editor-label">
            <label for="categories">Categories</label>
        </div>
        @foreach (var c in categories)
        {
            <input type="checkbox" name="categories" value="@c.CategoryId">
            @c.CategoryName
        }
        <p>
            <input type="submit" value="Create" class="submit" />
        </p>
    </fieldset>
}

当我尝试此代码时,ModeState.IsValid属性变为false(我通过调试看到)。但是,当我删除ModeState.IsValid时,插入操作已成功完成,一切正常我想要的工作 我需要ModeState.IsValid属性来验证我的视图。
更新:我的视图模型是;

[Key]
public int ProjectId { get; set; }
[Required(ErrorMessage="Please enter project heading")]
public string ProjectHeading { get; set; }
[Required(ErrorMessage = "Please enter project Url")]
public string ProjecctUrl { get; set; }
[Required(ErrorMessage = "Please enter project description")]
public string ProjectLongDescription { get; set; }
public string ProjectShortDescription
{
    get
    {
        var text = ProjectLongDescription;
        if (text.Length > ApplicationConfiguration.ProjectShortDescriptionLength)
        {
            text = text.Remove(ApplicationConfiguration.ProjectShortDescriptionLength);
            text += "...";
        }
        return text;
    }
}
public bool PromoFront { get; set; }
[Required(ErrorMessage = "You must sepcify a thumbnail")]
public string ProjectThubmnail { get; set; }
[Required(ErrorMessage = "You must select an image")]
public string ProjectImage { get; set; }
public int CategoryId { get; set; }
public IEnumerable<Category> Categories { get; set; }

更新2:我发现了错误。问题是

{System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'PortfolioMVC4.Models.Category' failed because no type converter can convert between these types.
   at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)
   at System.Web.Mvc.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo culture, Object value, Type destinationType)
   at System.Web.Mvc.ValueProviderResult.ConvertTo(Type type, CultureInfo culture)
   at System.Web.Mvc.DefaultModelBinder.ConvertProviderResult(ModelStateDictionary modelState, String modelStateKey, ValueProviderResult valueProviderResult, Type destinationType)}

2 个答案:

答案 0 :(得分:12)

在调试时,请检查ModelState是否有错误。它是一个键/值字典,包含使模型有效所需的所有属性。如果您检查Values - 属性,则可以找到Errors列表中非空的列表,并查看错误是什么。

Example of ModelState errors

或者在action方法中添加以下代码行以获取模型的所有错误:

var errors = ModelState.Where(v => v.Value.Errors.Any());

答案 1 :(得分:4)

您应该将categories操作参数重命名为其他内容,因为您的PortfolioViewModel模型已经有一个名为Categories的属性,该属性的类型完全不同,并且会混淆模型绑定器:

[HttpPost]
[Authorize(Roles = "Admin")]
public ActionResult ProjectAdd(
    PortfolioViewModel model, 
    int[] categoryIds, 
    HttpPostedFileBase thumbnail, 
    HttpPostedFileBase image
)
{
    ...
}

现在很明显,您还必须更新视图以匹配复选框名称。

虽然这可能会解决您的问题,但我强烈建议您使用视图模型并停止将域模型传递给视图。