Howcome我填充选择列表的使用类别列表 [英] Howcome I populate selectlist with list of categories
问题描述
我想要做的是填充的SelectList
从一个类别库类别。
小样机 http://mockupbuilder.com/App/15379 。
What I want to do is to populate SelectList
with categories from a categories repository.
A little mockup http://mockupbuilder.com/App/15379.
我现在已经是一个控制器:
What I have now is a controller:
[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);
}
类别类是这样的:
Category class is like this:
public class Category : AbstractEntity<Category> {
public String Title { get; set; }
public String Description { get; set; }
}
我如何填充的SelectList
?如何使这个使用 JSON
?
How do I populate a SelectList
? How do I make this using JSON
?
谢谢!
推荐答案
您可以将列表中viewbag和使用ASPX code渲染。喜欢的东西如下:
You can put the List in viewbag and render it using aspx code. Something like below:
[HttpGet]
public ActionResult Create() // your create page render action
{
Viewbag.CategoryList = categories.GetAll(); //put it into viewbag
return View();
}
而在你的视图页面,这样的事情:
And in your view page, something like this:
<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来填充类别。 你必须在你的类控制器就像写一个新动作:
If you want to populate the categories via json. You have to write a new action in your category controller like:
public class CategoryContrller : Controller{
....
[HttpGet]
public ActionResult GetAll()
{
var categories = categories.GetAll(); //put it into viewbag
return Json(categories, JsonRequestBehavior.AllowGet);
}
}
而在你的页面的js的逻辑,使用Ajax调用它和处理结果。
And in your page's js logic use ajax to call it and handle the result.
这篇关于Howcome我填充选择列表的使用类别列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!