よし、Chosen の jQuery バージョンを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);
}
次に、/Event/View/1
I haveに移動するときに、次の方法で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);
}
ご覧のとおり、モデルを次のモデルに設定します。
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;
}
}
最後に、ビューに次のマークアップがあります。
@Html.DropDownListFor(m => m.CategoryIds,
ViewBag.AvailableCategories as MultiSelectList,
new { multiple = "multiple", @class = "chzn-container" })
最初に述べたように、適切に表示され、期待どおりにすべてのカテゴリが一覧表示されています。ただし、CategoryIds
プロパティには実際には 2 つの選択されたカテゴリが一覧表示されますが、ロード時に [Chosen] ドロップダウンで選択されているように設定 (または表示) されません。
ユーザーがChosenドロップダウンから値を選択した場合、アイテムが選択されたときにHTMLが変更されないため、投稿時に適切にバインドされないことをさらに想定する必要があります.
それで、私の質問はこれです.MVCでChosenドロップダウンに適切に双方向データをバインドするにはどうすればよいですか?