我在将数据从视图发送回控制器时遇到问题。我对MVC很陌生,我无法弄清楚问题出在哪里。
这是视图:
@model IEnumerable<OnlineCarStore.Models.CategoriesVM>
<div class="container">
<div class="row">
@using (Html.BeginForm("SubCategory", "Product"))
{
<div class="list-group col-sm-3" style="width:280px;">
@{var selected = string.Empty;
if (@HttpContext.Current.Session["selectedCar"] == null)
{
selected = string.Empty;
}
else
{
selected = @HttpContext.Current.Session["selectedCar"].ToString();
}
foreach (var c in Model)
{
<a href="@Url.Action("SubCategory", "Product", new { selected = selected, id = @c.ID, category = @c.CategoryName })" id="link" class="list-group-item">
<span> @c.CategoryName</span>
</a>
for (int i = 0; i < c.Childrens.Count; i++)
{
@Html.HiddenFor(x => c.Childrens[i].Item)
@Html.HiddenFor(x => c.Childrens[i].Children)
}
}
}
这是我需要的数据的视图模型:
public class CategoriesVM
{
public int ID { get; set; }
public int AtpID { get; set; }
public string CategoryName { get; set; }
public List<Helpers.TreeItem<Categories>> Childrens { get; set; }
}
这是在控制器中:
public ActionResult SubCategory(IEnumerable<OnlineCarStore.Models.CategoriesVM> Model)
{
.在模型参数中,我需要 CategoriesVM 包含的所有数据,但模型参数始终为空。你能告诉我我做错了什么吗?我错过了什么?谢谢!
您不能(也不应该)通过链接单击传递 Category 对象的所有属性!仅当您的对象是倾斜平坦且属性很少时,它才有效。当你的对象很复杂时,这并不理想!
您只需将唯一的 Id(类别 ID)传递给下一个操作方法,并在其中使用此 id 查询所需的数据并使用该数据。
我还注意到您正在为循环中的链接设置相同的 id 值。它将生成多个具有相同 Id 值的锚标记。这是无效的 HTML。因此,让我们将其删除。
<a href="@Url.Action("SubCategory", "Product", new { id = @c.ID })"
class="list-group-item">
<span> @c.CategoryName</span>
</a>
现在在您的SubCategory
操作方法中
public ActionResult SubCategory(int id)
{
//using the id, get the data needed (may be the category & subcategories)
// to do : Return something
}