Mik*_*oud 6 .net c# jquery asp.net-mvc-4 jquery-chosen
好吧,我有一个jQuery版本的Chosen应用于select我的页面上的正确显示,我已经使用以下代码完成了.首先,我有一个BaseController设置ViewBag列出所有可能类别的属性:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
try
{
_connection.Open();
this.ViewBag.AvailableCategories = new MultiSelectList(_connection.Query<Category>("select * from Category"), "CategoryID", "Name");
}
catch (Exception ex)
{
throw new HttpException(500, ex.Message);
}
finally
{
_connection.Close();
}
base.OnActionExecuted(filterContext);
}
Run Code Online (Sandbox Code Playgroud)
接下来,当导航到/Event/View/1I 时,使用以下方法进行EventController设置(注意此控制器基于上述控制器)View.
public ActionResult View(int id)
{
Event evt = null;
try
{
evt = Event.Where(_connection, id);
if (evt == null)
{
throw new HttpException(404, "Oops! The event you're looking for does not exist.");
}
}
catch (Exception ex)
{
throw new HttpException(500, ex.Message);
}
return View(evt);
}
Run Code Online (Sandbox Code Playgroud)
如您所见,它将模型设置为以下模型.
public class Event
{
public int EventID { get; set; }
public int BusinessID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int NeighborhoodID { get; set; }
public IEnumerable<int> CategoryIds
{
get
{
if (Categories == null) { return new List<int>(); }
return Categories.Select(c => c.CategoryID).AsEnumerable();
}
}
public List<EventCategory> Categories { get; set; }
public List<EventHours> Hours { get; set; }
public static Event Where(IDbConnection connection, int id)
{
Event result = null;
try
{
connection.Open();
var sql =
@" select * from Event where EventID = @EventID
select * from EventCategory where EventID = @EventID
select * from EventHours where EventID = @EventID";
using (var multiResult = connection.QueryMultiple(sql, new { EventID = id }))
{
result = multiResult.Read<Event>().FirstOrDefault();
if (result != null)
{
result.Categories = multiResult.Read<EventCategory>().ToList();
result.Hours = multiResult.Read<EventHours>().ToList();
}
}
}
finally
{
connection.Close();
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
最后,我在视图中有以下标记.
@Html.DropDownListFor(m => m.CategoryIds,
ViewBag.AvailableCategories as MultiSelectList,
new { multiple = "multiple", @class = "chzn-container" })
Run Code Online (Sandbox Code Playgroud)
现在,正如我先说的那样,它正确显示并按预期列出所有类别.但是,即使该CategoryIds属性实际上列出了两个选定的类别,也不会在选择下拉列表中选择它们(或显示它们).
我不得不进一步假设,如果用户从Chosen下拉列表中选择了一个值,它将无法在post上正确绑定,因为它在选择项目时不会更改HTML.
所以,我的问题是,如何将正确的双向数据绑定到MVC中的Chosen下拉?
ListBoxFor是您应该用于多选列表的助手
替换
@Html.DropDownListFor(m => m.CategoryIds,
ViewBag.AvailableCategories as MultiSelectList,
new { multiple = "multiple", @class = "chzn-container" })
Run Code Online (Sandbox Code Playgroud)
和
@Html.ListBoxFor(m => m.CategoryIds,
ViewBag.AvailableCategories as MultiSelectList,
new { multiple = "multiple", @class = "chzn-container" })
Run Code Online (Sandbox Code Playgroud)
应该能解决问题
| 归档时间: |
|
| 查看次数: |
1513 次 |
| 最近记录: |