Howcome I populate selectlist with list of categories

丶灬走出姿态 提交于 2020-01-15 10:40:07

问题


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; }
}

How do I populate a SelectList? How do I make this using JSON?

Thanks!


回答1:


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>

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);
    }
}

And in your page's js logic use ajax to call it and handle the result.



来源:https://stackoverflow.com/questions/10649081/howcome-i-populate-selectlist-with-list-of-categories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!