Имеется модель:
public enum Type
{
Phone, Tablet, Car, Other
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Type? Type { get; set; }
public string Description { get; set; }
public DateTime AddDate { get; set; }
public int Price { get; set; }
}
ну и View:
@using BROCKHAUS_AG_Test_Web_App.Models
@model Product
@{
ViewBag.Title = "Create product";
}
<h2>New product</h2>
@using (Html.BeginForm("Create", "Product", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(m => m.Name, "Product name", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(m => m.Name, new { htmlAttributes = new { @class = "form-control", @name = "firstField" } })
@Html.ValidationMessageFor(m => m.Name)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Type, "Product type", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EnumDropDownListFor(m => m.Type, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Type, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Description, "Description", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(m => m.Description, new { htmlAttributes = new { @class = "form-control", @name = "firstField" } })
@Html.ValidationMessageFor(m => m.Description)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Price, "Price", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(m => m.Price, new { htmlAttributes = new { @class = "form-control", @name = "firstField" } })
@Html.ValidationMessageFor(m => m.Price)
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Send" class="btn btn-default" />
</div>
</div>
}
При отправке модели в контроллер, в методе Create:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Name, Description, Price")] Product product)
{
try
{
if (ModelState.IsValid)
{
product.AddDate = DateTime.Now;
productRepository.InsertProduct(product);
productRepository.Save();
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
}
return View(product);
}
значение product.Type
равно null
, хотя я, вроде, его проинициализировал во Create и оправил целиком в ProductController.
Буду счастлив узнать как передать это значение в контроллер.
[Bind(Include = "Name, Description, Price")]
- гдеType
?<td>@Html.ActionLink(product.Type.ToString(), "FilteredProducts", "Product", product.Type)</td>
в методеpublic ActionResult FilteredProducts([Bind(Include = "Type")] Models.Type? searchType) { ...}
параметр searchType равен null. Что не так делаю?Type =
в Create, по крайней мере явного. если есть неявное в InsertProduct - посмотрите ответ по ссылке выше.