ASP.NET MVC 3 - Html.DropDownList for Enumerated values - asp.net-mvc-3

I'm new to ASP.NET MVC 3. I'm trying to display some options in a drop down list. The options will mimic values in an enum. The enum has the following three values:
public enum Gender
{
Male = 0,
Female = 1,
NotSpecified=-1
}
I am trying to generate the following HTML
<select>
<option value="0">Male</option>
<option value="1">Female</option>
<option value="2">Not Specified</option>
</select>
I'm trying to do this with Razor, but i'm a bit lost. Currently I have:
#Html.DropDownList("relationshipDropDownList", WHAT GOES HERE?)
Please note, I cannot edit the enum. Thank you for your help!

something like this...
//add this to your view model
IEnumerable<SelectListItem> genders = Enum.GetValues(typeof(Gender))
.Cast<Gender>()
.Select(x => new SelectListItem
{
Text = x.ToString(),
Value = x.ToString()
});
#Html.DropDownList("relationshipDropDownList", Model.genders)

There is an answer to the same question here
The accepted answer has an extension method to convert the enum into a selectlist, which can be used like this
In the controller
ViewBag.Relationships = Gender.ToSelectList();
in the partial
#Html.DropDownList("relationshipDropDownList", ViewBag.Relationships)

#Html.DropDownList("relationshipDropDownList", Model.GenderSelectList);
However, I would rather use DropDownListFor to avoid using magic strings:
#Html.DropDownListFor(m => m.relationshipDropDownList, Model.GenderSelectList);
and in the ViewModel you'd build your SelectListItems
public static List<SelectListItem> GenderSelectList
{
get
{
List<SelectListItem> genders = new List<SelectListItem>();
foreach (Gender gender in Enum.GetValues(typeof(Gender)))
{
genders.Add(new SelectListItem { Text = gender.ToString(), Value = gender.ToString("D"), Selected = false });
}
return genders;
}
}

public enum EnumGender
{
Male = 0,
Female = 1,
NotSpecified = -1
}
#Html.DropDownList("relationshipDropDownList", (from EnumGender e in Enum.GetValues(typeof(EnumGender))
select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), "select", new { #style = "" })
//or
#Html.DropDownList("relationshipDropDownList", (from EnumGender e in Enum.GetValues(typeof(EnumGender))
select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), null, new { #style = "" })

Related

Using Devexpress MVC TreeList to list order totals by client

I'm trying to implement a DevExpress MVC TreeList that shows a list of clients as the first level of the hierarchy. But when you open one client, the second level must show a list of related orders with their OrderTotal for each order.
I'm trying to base myself on the demo at http://demos.devexpress.com/MVCxTreeListDemos/DataBinding/DataBinding which is similar to what I'm looking for. I'm using the Northwind database as an example.
The model that the TreeList must be based on has to be specific in that it has to have the following structure (maybe I'm wrong on this):
CustomerId,
Order.CustomerId,
CustomerName,
OrderTotal,
OrderDate,
ShipCity
The second one has to be the "ParentId" in order to satisfy the hierarchy structure.
Here is what I have in my controller:
[ValidateInput(false)]
public ActionResult OrderTreeListPartial()
{
var model = db.Orders.GroupBy(o => o.Customer)
.Select(group => new
{
CustomerId = group.Key.CustomerID,
ParentId = group.Select(g=>g.CustomerID),
CustomerName = group.Key.CompanyName,
OrderTotal = group.Sum(g => g.OrderTotal),
OrderDate = group.Select(g => g.OrderDate),
City = group.Select(g => g.ShipCity)
});
return PartialView("_OrderTreeListPartial", model);
}
And I have the following in my _OrderTreeListPartial:
#{
var treeList = Html.DevExpress().TreeList(settings =>
{
settings.Name = "OrderTreeList";
settings.CallbackRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartial" };
settings.SettingsEditing.AddNewNodeRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartialAddNew" };
settings.SettingsEditing.UpdateNodeRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartialUpdate" };
settings.SettingsEditing.DeleteNodeRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartialDelete" };
settings.SettingsEditing.NodeDragDropRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartialMove" };
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.AutoGenerateColumns = false;
settings.KeyFieldName = "CustomerId";
settings.ParentFieldName = "ParentId";
settings.RootValue = 0;
settings.Columns.Add(
column =>
{
column.FieldName = "CustomerName";
}
);
settings.Columns.Add(
column =>
{
column.FieldName = "OrderDate";
}
);
settings.Columns.Add(
column =>
{
column.FieldName = "OrderTotal";
column.PropertiesEdit.DisplayFormatString = "{0:C}";
}
);
settings.Columns.Add(
column =>
{
column.FieldName = "City";
}
);
settings.SettingsPager.Visible = true;
settings.SettingsSelection.Enabled = true;
});
if (ViewData["EditError"] != null)
{
treeList.SetEditErrorText((string)ViewData["EditError"]);
}
}
#treeList.Bind(Model).GetHtml()
I think the problem is in my LINQ expression in my controller. The truth is I'm not an expert in LINQ and I'm evaluating the DevExpress extensions for a future project. Any help would be appreciated, wether in my LINQ or in how I prepared the TreeList.
You didn't really specify your problem but I think you shouldn't do the grouping in advance as this results in list of groups.
Just create a DataTable with the columns "CustomerId" and "ParentId".
The TreeList will then do the grouping

MVC ListBox Selected Values

New to MVC and Stackoverflow so sorry for not having enough reputation to post images...
Trying to render a ListBox with pre selected values
My SQL Database:
http://i.imgur.com/bcdXyqE.png
My Entity Framework
http://i.imgur.com/wYWXuAq.png
My Controller
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
var roles = db.Role;
var newList = new List<SelectListItem>();
foreach (var role in roles)
{
newList.Add(
new SelectListItem()
{
Value = role.Id.ToString(),
Text = role.RoleName,
Selected = user.Role.Contains(role)
}
);
}
ViewBag.x = new SelectList(newList, "Value", "Text");
ViewBag.Roles = new SelectList(db.Role, "Id", "RoleName", user.Role);
return View(user);
}
My View
<p>try1:</p>
#Html.ListBox("Roles", null, new { #class = "form-control", #size = 6, #style = "height: initial" })
<p>try2:</p>
#Html.ListBox("x", null, new { #size = 6, #style = "height: initial" })
Non of the 2 tries renders with pre selected values?
got it working.
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
IEnumerable<SelectListItem> roles = db.Role.Select(c => new SelectListItem{ Value = c.Id.ToString(), Text = c.RoleName, Selected = true});
var rolesSelected = new int[user.Role.Count];
var i = 0;
foreach (var role in user.Role)
{
rolesSelected[i] = role.Id;
i++;
}
ViewBag.Roles = roles.ToList();
ViewBag.RolesSelected = rolesSelected;
return View(user);
}
#Html.ListBox("RolesSelect", new MultiSelectList(ViewBag.Roles, "Value", "Text", ViewBag.RolesSelected), new { #class = "form-control", #size = 6, #style = "height: initial" })

How to Bind dropdown from anonymous class values

I want to populate a dropdown with values A,Band C.The below code works for create only,not for edit.
ViewBag.UserType = new[] { new SelectListItem { Text = "A", Value = "1", Selected = false }, new SelectListItem { Text = "B", Value = "2", Selected = false }, new SelectListItem { Text = "C", Value = "3", Selected = false } };
So I created an anonymous class. I have an anonymous class like below.
var Roles= new[]
{ new { Id =1,UserType="A" },
new {Id=2,UserType="B" },
new {Id=3,UserType="B" }
};
ViewBag.Type = Roles.ToList();
But i dont know how to fill dropdown in View.
#Html.DropDownListFor(model => model.UserType, ((IEnumerable<SelectListItem>)ViewBag.UserType).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Text),
Value = option.Value.ToString(),
Selected = (Model != null) && (option.Value == (Model.UserType).ToString())
}),"Select")
What changes should i make in the view
Add following properties to your ViewModel class -
public SelectList Roles
{
get
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem
{
Value = "1",
Text = "A",
});
items.Add(new SelectListItem
{
Value = "2",
Text = "B",
});
items.Add(new SelectListItem
{
Value = "3",
Text = "C",
});
return new SelectList(items, "Value", "Text");
}
}
public int SelectedRole { get; set; }
and bind in View as follows -
#Html.DropDownListFor(model => model.SelectedRole, Model.Roles)

Bind Telerik DDL

I am trying to bind a Telerik DropDownList.
View Code:
<div>#( Html.Telerik().DropDownList()
.Name("ddlCounty")
.HtmlAttributes(new { style = "width:200px;" })
.SelectedIndex(0)
.BindTo(new SelectList((IEnumerable<MvcNew.Models.tbl_Country>)ViewData["ListCountries"], "Value", "Text")) )
</div>
Controller Code:
List<SelectListItem> lst_Country = new List<SelectListItem>();
var Countries = (from m in DBContext.tbl_Countries
select new SelectListItem{ Text = m.Country__Name.ToString(), Value = m.Country_ID.ToString() });
ViewBag.ListCountries = new SelectList(Countries);
return View();
I am getting the below error
Unable to cast object of type 'System.Web.Mvc.SelectList' to type 'System.Collections.Generic.IEnumerable`1[MvcNew.Models.tbl_Country]'.
I have changed a code like this and it's worked
var clientIDs = DBContext.tbl_Countries
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in clientIDs)
{
SelectListItem s = new SelectListItem();
s.Text = t.Country__Name.ToString();
s.Value = t.Country__Name.ToString();
items.Add(s);
}
ViewBag.ListCountries = items;

Load data in Telerik grid by dropdownlist selected value

I am a beginner in Telerik Grid in ASP.NET MVC3. I try to bind Grid with dropdownlist selected value. Please see my code below.
My web model class
public class CustomerEventRolesModels
{
public int Event { get; set; }
public IEnumerable<System.Web.Mvc.SelectListItem> Events { get; set; }
public Telerik.Web.Mvc.GridModel<CustomerEventRolesModel> GridData { get; set; }
}
public class CustomerEventRolesModel : BaseNopEntityModel
{
public string Customer { get; set; }
public bool Sponsor { get; set; }
public bool Speaker { get; set; }
}
My .cshtml
<table id="grdCustomerEventRoleData" class="adminContent" style="display: none">
<tr>
<td>
<p>
</p>
</td>
</tr>
<tr>
<td>
#(Html.Telerik().Grid<CustomerEventRolesModel>(Model.GridData.Data)
.Name("grdCustomerEventRoles")
.Columns(columns =>
{
columns.Bound(x => x.Customer);
columns.Bound(x => x.Speaker).Template(x => Html.CheckBox("spk", x.Speaker));
columns.Bound(x => x.Sponsor).Template(x => Html.CheckBox("spn", x.Sponsor));
}
) .Pageable(settings => settings.Total(Model.GridData.Total)
.PageSize(gridPageSize)
.Position(GridPagerPosition.Both))
.ClientEvents(events => events.OnDataBinding("onDataBinding"))
.DataBinding(dataBinding => dataBinding.Ajax().Select("FilterByDropdown", "Customer"))
.EnableCustomBinding(true))
) )
</td>
</tr>
<script type="text/javascript">
var initialLoad = true;
$("#select-event").change(function () {
if ($("#select-event option:selected").val() > 0) {
$("#grdCustomerEventRoleData").show();
$("#grdCustomerEventRoles").data("tGrid").rebind();
}
else {
$("#grdCustomerEventRoleData").show();
}
});
function onDataBinding(e) {
if (initialLoad == true) {
e.preventDefault();
initialLoad = false;
}
else {
var classificationId = $("#select-event option:selected").val();
if (classificationId != "")
e.data = $.extend(e.data, {
selEvent: classificationId
});
else {
e.preventDefault();
$("#grdCustomerEventRoleData").hide();
}
}
}
Actions in controller
public ActionResult FirstBind()
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers))
return AccessDeniedView();
var model = new CustomerEventRolesModels();
model.Event = 0;
List<Nop.Core.Domain.Catalog.Product> products = _productRepository.Table.Where(p => p.EventDate != null && p.EventDate >= DateTime.Now).ToList();
model.Events = products.Select(p => new System.Web.Mvc.SelectListItem
{
Text = p.Name,
Value = p.Id.ToString()
});
var grdmodel = new GridModel<CustomerEventRolesModel>
{
Data = null,
Total = 0
};
model.GridData = grdmodel;
return View(model);
}
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult FilterByDropdown(GridCommand command, int selEvent)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers))
return AccessDeniedView();
if (selEvent == 0)
return View();
var model = new CustomerEventRolesModels();
model.Event = selEvent;
var roles = (from lst in _customerEventRoleRepository.Table
join cust in _customerRepository.Table on lst.CustomerId equals cust.Id
join product in _productRepository.Table on lst.EventId equals product.Id
join role in _customerRoleRepository.Table on lst.RoleId equals role.Id
orderby lst.Id descending
select new CustomerEventRolesModel
{
Id = lst.Id,
Customer = cust.Email,
Sponsor = (role.Name == "Sponsor") ? true : false,
Speaker = (role.Name == "Speaker") ? true : false
}).ToList();
var grdmodel = new GridModel<CustomerEventRolesModel>
{
Data = roles,
Total = roles.Count
};
model.GridData = grdmodel;
return new JsonResult
{
Data = model
};
}
FilterByDropdown action is works correctly but Grid is not binded.
I am clueless.
Please help.
If you want to add a dropdown to a Telerik MVC Grid when editing a row, you will need to follow next few steps (aside from making the grid ajax bound and the rows editable).
Let’s say we want the column representing a name (“Name” from the model) to be a dropdown, from which a name can be selected rather than typed. Add a folder named “EditorTemplates” to the folder containing the view that the grid is on. It will contain a separate partial view for each dropdown we want to show in the row that is being edited. Make a partial view (mentioned above), name it e.g. “ClientName.cshtml”, containing a Telerik DropDownList named “Name” and bound to required list of names.
#(Html.Telerik().DropDownList()
.Name("Name")
.BindTo(new SelectList((IEnumerable)ViewData["CustomerNames"], "Text", "Value"))
)
Add the following attribute to the “Name” property of the data type that the grid uses e.g. Grid uses “Customer” class, containing “string Name” field:
public class Customer{ [UIHint("ClientName"), Required] public string Name { get; set; } }
The UIHint property specifies which field template to use when a specific column is rendered.
Add the following java script to the page containing the grid function:
function onEditCustomerList(e) { if (e.dataItem != null) { $(e.form).find('#Name').data('tDropDownList').select(function (dataItem) { return dataItem.Text == e.dataItem['Name']; });
} }
This should do the trick.
You're returning the wrong model.
Try this in FilterByDropdown:
var grdmodel = new GridModel<CustomerEventRolesModel>
{
Data = roles,
Total = roles.Count
};
return new JsonResult
{
Data = grdmodel
};

Resources