2016-08-24 2 views
-2

У меня есть моя модель и мой взгляд. Все работает нормально. Единственная проблема заключается в том, что он не показывает предупреждающий знак, как ожидалось. Я добавил аннотацию данных в модель.модель не проверяется перед отправкой POST

Если требуемое поле остается пустым, я получаю сообщение об ошибке. Я ожидаю, что если что-то потребуется, он не будет подавать, и он покажет предупреждающий знак.

Это моя модель:

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 
     { 
      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 }); 
} 
+0

Какое предупреждение вы говорите? Когда вы ожидаете, что это появится? – Shyju

+0

предупреждение о валидации – coco

ответ

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> 
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 
} 
+0

Это не помогает. – coco

+0

Что происходит с этим изменением кода? Представлена ​​ли ваша форма без заполнения всех необходимых полей? Что происходит? – Shyju

+1

@coco Ваш комментарий не помогает. Мы не можем смотреть на ваш экран. Вам нужно прочитать [ask] и явно объяснить, что вы ожидаете, что происходит на самом деле, и что вы пытались разрешить различия между ними. – CodeCaster

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 }); 
     } 
+0

Это не работает. – coco

+0

вы можете получить модель, а затем проверить ModelState.IsValid, а затем связать данные модели с доменом, а затем сохранить в db –

Смежные вопросы