【发布时间】:2017-02-09 05:18:04
【问题描述】:
我正在努力更好地了解和了解 MCV4。
将我的 Product 对象的属性 CategoryType 传递回 HttpPost 上的控制器的最佳方法是什么。
我正在寻找一种方法,这样我就不必手动写出每个属性。 我目前正在使用反射来迭代 Category 类型的属性,并使用 @Html.Hidden 方法将它们添加为隐藏输入变量。 这行得通,但我想知道我的做法是否正确(最佳做法)。
- 我想知道如何使用@Html.HiddenFor 方法实现我在下面所做的事情。我不知道如何使用反射中的属性信息编写 lambda 表达式。
- 有没有更好的方法来处理将 Category 对象传递给我的控制器。我的观点是强类型的。它是否应该知道在帖子中传回 Product 对象。
我有一个复杂类型如下。
public class Product
{
[Key]
public int Id { get; set; }
[Required]
public string ProductName { get; set; }
public Category CategoryType { get; set; }
}
public class Category
{
[Key]
public int Id { get; set; }
[Required]
public string CategoryName { get; set; }
}
使用如下控制器
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index()
{
return View();
}
public ActionResult Add()
{
//Add a new product to the cheese category.
var product = new Product();
var category = new Category { Id = 1, CategoryName = "Cheese" };
product.CategoryType = category;
return View(product);
}
[HttpPost]
public ActionResult Add(Product product)
{
if (ModelState.IsValid)
{
//Add to repository code goes here
//Redirect to Index Page
return RedirectToAction("Index");
}
return View(product);
}
}
加上添加视图
@model BootstrapPrototype.Models.Product
@{
ViewBag.Title = "Add";
}
<h2>Add</h2>
@using (Html.BeginForm())
{
@Html.DisplayFor(m => m.ProductName);
@Html.EditorFor(m => m.ProductName);
foreach(var property in Model.CategoryType.GetType().GetProperties())
{
//I know how to use the Hidden but would also know how to use the HiddenFor with reflections.
@Html.Hidden("CategoryType." + property.Name, property.GetValue(Model.CategoryType));
}
<button type="submit">Add</button>
}
谢谢。
【问题讨论】:
标签: asp.net-mvc-4