Monday, September 3, 2012

How to Use @ViewData with HTML attributes - MVC 3 with Razor views

How to Use @ViewData with HTML attributes - MVC 3 with Razor views
How to use ViewDataDictionary
Most of the time developers need this trick when making common views.
this is a complete code section about how to use common partial views.

-My Custom PartialView for a SelectList (Shared/MultiSelectList.cshtml)
@model IEnumerable <SharedModels.CustomSelectListItem>

<select name="@ViewData["name"]" id="@ViewData["id"]" multiple="multiple" data-native-menu="false" tabindex="-1">

<option>@ViewData["defaultOption"] < /option>
< option value="0" > All < /option>
@foreach (var item in Model)
{
< option value="@item.value" > @item.name < /option>
}
</select>





-Main Partial VIEW (/SearchPanel.cshtml)

< input type="text" id="@(ViewBag.Mod)_search_text" name="name" value=""/ >

@*below code will call my custom partial view with viewdatadictionary parameters*@

@{Html.RenderPartial("MultiSelectList", (IEnumerable)ViewBag.pp, new ViewDataDictionary { { "id", "search_select_privacy" }, { "name", "select_privacy" }, { "defaultOption", "Privacy Type(s)" } });}

<a href="#" data-role="button" id="@(ViewBag.Mod)_searchkey" > Search

- Controller

public PartialViewResult SearchBox(string Mod)
{
ViewBag.Mod = Mod;

ViewBag.pp = new List {
new CustomSelectListItem{value=1,name="public"},
new CustomSelectListItem{value=2,name="private"},
new CustomSelectListItem{value=3,name="global"}
};

return PartialView("~/Views/Shared/SearchPanel.cshtml");
}