模型在POST之前未验证

时间:2016-08-24 17:36:10

标签: c# asp.net-mvc asp.net-mvc-4 data-annotations

我有我的模特和观点。一切都很好。唯一的问题是它没有按预期显示警告标志。我在模型中添加了数据注释。

如果需要的字段保持为空,则会出错。我希望如果需要的东西搞乱它就不会提交,它会显示警告标志。

这是我的模特:

public partial class RecipeV
{
    [Display(Name = "Title")]
    [Required(ErrorMessage = "Title required")]
    public string Title { get; set; }

    [Required(ErrorMessage = "Description required")]
    [StringLength(5)]
    [Display(Name = "Description")]
    public string Description { get; set; }

    public IngredientV Ingredient { get; set; }

    public DirectionV Direction { get; set; }
}

这是我的观点:

@model RecipesBlog.Models.ViewModels.RecipeV

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Create Recipe</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Ingredient.Text, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @for (int i = 0; i < 3; i++)
                {
                    <p> <input class="form-control" type="text" name="Ingredient[@i].Text"><br></p>
                }
                <div class="Ingredient"></div>

                <input class="add_Ingredient" type="text" value="&#43" />

                @Html.ValidationMessageFor(model => model.Ingredient.Text, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            @Html.LabelFor(model => model.Direction.Text, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @for (int i = 0; i < 3; i++)
                {
                    <p> <input class="form-control" type="text" name="Direction[@i].Text"><br></p>
                }
                <div class="Directions"></div>

                <input class="add_Direction" type="text" value="&#43" />

                @Html.ValidationMessageFor(model => model.Direction.Text, "", new { @class = "text-danger" })

            </div>

        </div>



    <div class="form-group">

    </div>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>

</div>
}

这是控制器:

[HttpPost]
public ActionResult Create(Recipe recipe, List<Ingredient> ingredient, List<Direction> direction)

我添加了一个try catch,所以如果有错误,它将不会提交。

        try
        {
            recipe.Date = DateTime.Now;
            // Add the new recipe to the recipes table.
            db.Recipes.InsertOnSubmit(recipe);
            db.SubmitChanges();
        }
        catch
        {
           return View();
        }

    int id = recipe.RecipeID;

    foreach (Ingredient i in ingredient)
    {
        if (i.Text != null)
        {
            i.RecipeID = id;
            db.Ingredients.InsertOnSubmit(i);
            db.SubmitChanges();
        }               
    }

    foreach (Direction d in direction)
    {
        if (d.Text != null)
        {
            d.RecipeID = id;
            db.Directions.InsertOnSubmit(d);
            db.SubmitChanges();
        }
    }

    //Direct the user to the index page. 
    return RedirectToAction("index", "Recipes", new { id = recipe.RecipeID });
}

3 个答案:

答案 0 :(得分:2)

您的Create HttpPost操作方法中的当前代码会尝试保存数据并执行重定向,这是一个新的GET调用。如果要在提交的表单中查看验证错误,则应返回相同的视图。 Modelstate字典将具有验证错误(如果有),并且在呈现视图时,它们将被显示。

最好在继续保存数据之前检查ModelState.IsValid属性以查看模型验证是否失败。

[HttpPost]
public ActionResult Create(Recipe recipe, List<Ingredient> ingredient,
                                                                  List<Direction> direction)
{
    if (!ModelState.IsValid)
       return View(vm);   // validation failed. Return the same view

    //continue executing your save & redirect code
}

答案 1 :(得分:1)

此外,您应该收到RecipeV模型而不是域名。

[HttpPost]
        public ActionResult Create(RecipeV model, List<Ingredient> ingredient, List<Direction> direction)
        {

            if (!ModelState.IsValid)
            {
                return View(model);
            }
           // do something
            //Direct the user to the index page. 
            return RedirectToAction("index", "Recipes", new { id = recipe.RecipeID });
        }

答案 2 :(得分:0)

所以这就是我所做的:

我下载了js验证文件,并在视图末尾添加了它。正如@Shyju所推荐,谢谢大家的帮助。

<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

它的外观如下:

@model RecipesBlog.Models.ViewModels.RecipeV
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Create Recipe</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Ingredient.Text, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @for (int i = 0; i < 3; i++)
                {
                    <p> <input class="form-control" type="text" name="Ingredient[@i].Text"><br></p>
                }
                <div class="Ingredient"></div>

                <input class="add_Ingredient" type="text" value="&#43" />

                @Html.ValidationMessageFor(model => model.Ingredient.Text, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            @Html.LabelFor(model => model.Direction.Text, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @for (int i = 0; i < 3; i++)
                {
                    <p> <input class="form-control" type="text" name="Direction[@i].Text"><br></p>
                }
                <div class="Directions"></div>

                <input class="add_Direction" type="text" value="&#43" />

                @Html.ValidationMessageFor(model => model.Direction.Text, "", new { @class = "text-danger" })

            </div>

        </div>



    <div class="form-group">

    </div>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>

</div>
}

<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>