2016-08-24 3 views
-2

내 모델과 내보기가 있습니다. 모든 것이 잘 작동합니다. 유일한 문제는 경고 기호가 예상대로 표시되지 않는 것입니다. 모델에 데이터 주석을 추가했습니다.POST 전에 모델이 유효하지 않음

필요한 필드가 비어있는 경우 오류가 발생합니다. 나는 뭔가가 엉망이라면 제출하지 않을 것이고 경고 신호를 보일 것이라고 기대한다.

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

나는 그것을하지 않습니다 그래서 지금 시도 캐치를 추가 :이 컨트롤러

@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> 
} 

: 이것은 내이다

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; } 
} 

:

내 모델입니다 오류가 있으면 제출하십시오.

 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

그래서 이것은 내가 한 일이다. @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

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

@ 코코 귀하의 의견은 도움이되지 않습니다. 우리는 당신의 화면을 볼 수 없다. 당신은 [ask]를 읽고 당신이 무엇을 기대하는지, 실제로 일어나는 것과 당신이이 둘의 차이점을 해결하려고 노력했는지를 매우 분명히 설명 할 필요가 있습니다. – CodeCaster

1

또한 도메인이 아닌 RecipeV 모델을 받아야합니다.

내가 JS 검증 파일을 다운로드하여보기의 마지막에 추가 :

[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에 저장할 수 있습니다. –