1

我想要做的是SelectList从类别存储库中填充类别。一个小样机http://mockupbuilder.com/App/15379

我现在拥有的是一个控制器:

[HandleError]
public class ProductController : Controller {
    private IRepository<Product> exhibitions;
    private IRepository<Category> categories;
    private readonly Int32 PageSize = 18;

    // ctor ...

    [HttpPost]
    public ActionResult Create(Product product, Guid categoryId) { 
        // validation ...
        // properties setting ...            
        product.Category = categories.Get(categoryId);
        return View(product);
    }

类别类是这样的:

public class Category : AbstractEntity<Category> {
    public String Title { get; set; }
    public String Description { get; set; }
}

我如何填充一个SelectList?我该如何使用JSON

谢谢!

4

1 回答 1

2

您可以将列表放入 viewbag 并使用 aspx 代码呈现它。如下所示:

[HttpGet]
public ActionResult Create() // your create page render action
{
    Viewbag.CategoryList = categories.GetAll(); //put it into viewbag

    return View();
}

在您的视图页面中,是这样的:

<select name="categoryId"> <%-- use name attribute to bind action parameters and model --%>
<%foreach (Category item in Viewbag.CategoryList)
  { %>
<option value="<%=item.Id %>"><%=item.Title %></option>
<% } %>
</select>

如果你想通过 json 填充类别。您必须在类别控制器中编写一个新操作,例如:

public class CategoryContrller : Controller{
    ....

    [HttpGet]
    public ActionResult GetAll()
    {
        var categories = categories.GetAll(); //put it into viewbag

        return Json(categories, JsonRequestBehavior.AllowGet);
    }
}

并在您页面的 js 逻辑中使用 ajax 来调用它并处理结果。

于 2012-05-18T08:33:06.573 回答