У меня есть моя модель и мой взгляд. Все работает нормально. Единственная проблема заключается в том, что он не показывает предупреждающий знак, как ожидалось. Я добавил аннотацию данных в модель.модель не проверяется перед отправкой 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="+" />
@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="+" />
@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 });
}
Какое предупреждение вы говорите? Когда вы ожидаете, что это появится? – Shyju
предупреждение о валидации – coco