Bind Telerik DDL - drop-down-menu

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;

Related

How to control null LookUp or Compare different types of List

I have something like this which is getting string categories (from dropdown).
I am taking all list in catList and comparing that item in string[]categories and if it is null add this to newCategories for add to database. And lastly i want to return List<Category> with categories values.
public List<Category> ExistingCategories(string[] categories)
{
var catList = GetAllCategories().ToList();
List<Category> newCategories = new List<Category>();
var existedCategory = catList.ToLookup(x=>x.Name , v=>v.Name);
foreach (var item in categories)
{
var lookUpExistedCategory = existedCategory[item];
if (lookUpExistedCategory != )
{
newCategories.Add(new Category { Name = item });
}
}
CreateCategories(newList);
return GetAllCategories().ToList();
}
How should I do that?
You can use .Contains(TKey value)
So you can replace your foreach loop by
var newCategories = categories
.Where(m => !existedCategory.Contains(m))
.Select(m => new Category{Name = m}).toList()
By the way, I don't see the need of a LookUp<TKey, TValue>, you could use a HashSet<T>
var existedCategory = new HashSet(GetAllCategories().Select(x => x.Name).ToList());
So your method would be
public List<Category> ExistingCategories(string[] categories)
{
var existingCategories = new HashSet(GetAllCategories().Select(x => x.Name).ToList());
var newCategories = categories
.Where(m => !existingCategories .Contains(m))
.Select(m => new Category{Name = m}).toList());
//assuming this method will add and save to your db
CreateCategories(newCategories);
return GetAllCategories().ToList();
}

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 open a View in PopUp in MVC 3

I am using MVC 3, in my project i have 2 view, i want to open 2nd view in 1st View popup
My 1st View is by that i want to Open 2nd View in PopUp,
#model CustomerAddressListModel
#using Nop.Web.Models.Customer;
#{
Layout = "~/Views/Shared/_ColumnsTwo.cshtml";
//title
Html.AddTitleParts(T("PageTitle.Account").Text);
}
<script type="text/javascript">
$(function () {
$('a.dialog').click(function () {
var url = $(this).attr('href');
var dialog = $('<div style="display:none"></div>').appendTo('body');
dialog.load(url, {}, function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog({
close: function (event, ui) {
dialog.remove();
}
});
});
return false;
});
});
</script>
<div class="add-btn-cntrnr left" style="width:400px;">
#Html.ActionLink("AddLink", "AddressAdd", "Customer", new { #class = "dialog" })
</div>
and this is my second view which i want to open in PopUp:
#model CustomerAddressEditModel
#using Nop.Web.Models.Customer;
#{
Layout = null;
}
#using Nop.Web.Framework;
#using (Html.BeginForm())
{
<div class="emai_head">
<span class="emai_head_text">Add Address</span>
#{
var dataDictAddress = new ViewDataDictionary();
//Merge ModelState (required for validation)
dataDictAddress.ModelState.Merge(ViewData.ModelState);
dataDictAddress.TemplateInfo.HtmlFieldPrefix = "Address";
#Html.Partial("_CreateOrUpdateAddress", Model.Address, dataDictAddress)
}
<input type="submit" class="acc_btnn" value=" " />
</div>
}
This is my controller for PopUp view :
[NopHttpsRequirement(SslRequirement.Yes)]
public ActionResult AddressAdd()
{
if (!IsCurrentUserRegistered())
return new HttpUnauthorizedResult();
var customer = _workContext.CurrentCustomer;
var model = new CustomerAddressEditModel();
model.NavigationModel = GetCustomerNavigationModel(customer);
model.NavigationModel.SelectedTab = CustomerNavigationEnum.Addresses;
model.Address = new AddressModel();
//countries
model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries())
model.Address.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString() });
model.Address.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });
return View(model);
}
[HttpPost]
public ActionResult AddressAdd(CustomerAddressEditModel model)
{
if (!IsCurrentUserRegistered())
return new HttpUnauthorizedResult();
var customer = _workContext.CurrentCustomer;
model.NavigationModel = GetCustomerNavigationModel(customer);
model.NavigationModel.SelectedTab = CustomerNavigationEnum.Addresses;
if (ModelState.IsValid)
{
var address = model.Address.ToEntity();
address.CreatedOnUtc = DateTime.UtcNow;
//some validation
if (address.CountryId == 0)
address.CountryId = null;
if (address.StateProvinceId == 0)
address.StateProvinceId = null;
customer.Addresses.Add(address);
_customerService.UpdateCustomer(customer);
// return RedirectToRoute("CustomerAddresses");
}
//If we got this far, something failed, redisplay form
//countries
model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries())
model.Address.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString(), Selected = (c.Id == model.Address.CountryId) });
//states
var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value).ToList() : new List<StateProvince>();
if (states.Count > 0)
{
foreach (var s in states)
model.Address.AvailableStates.Add(new SelectListItem() { Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.Address.StateProvinceId) });
}
else
model.Address.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });
return View(model);
}

ASP.NET MVC 3 - Html.DropDownList for Enumerated values

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 = "" })

DropdownListFor default value

Is there a simple way to add a "--Please select--" default option to a DropDownListFor in MVC 3?
So, I did something like this:
#Html.DropDownListFor(model => model.Dessert,
new SelectList(Model.AvailableDesserts, "DessertID", "DessertName"),
"---Select A Dessert ---")
Seems to work pretty well. Dessert in my viewmodel is the one selected by the user. AvailableDesserts is a collection of ones to pick from.
I have a couple extension methods on SelectList
public static SelectList PreAppend(this SelectList list, string dataTextField, string selectedValue, bool selected=false)
{
var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Selected = selected, Text = dataTextField, Value = selectedValue });
items.AddRange(list.Items.Cast<SelectListItem>().ToList());
return new SelectList(items, "Value", "Text");
}
public static SelectList Append(this SelectList list, string dataTextField, string selectedValue, bool selected=false)
{
var items = list.Items.Cast<SelectListItem>().ToList();
items.Add(new SelectListItem() { Selected = selected, Text = dataTextField, Value = selectedValue });
return new SelectList(items, "Value", "Text");
}
public static SelectList Default(this SelectList list,string DataTextField,string SelectedValue)
{
return list.PreAppend(DataTextField, SelectedValue, true);
}
Then my razor looks like:
#Html.DropDownListFor(m=>m.SelectedState,
Model.StateList().Default("Select One",""))
Hi what about trying this (in case you use DisplayFor method)
private IEnumerable<SelectListItem> AddDefaultOption(IEnumerable<SelectListItem> list, string dataTextField, string selectedValue)
{
var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = dataTextField, Value = selectedValue});
items.AddRange(list);
return items;
}
Then just add this code to your Controller
//lambda expression binding
ViewBag.YourList = db.YourTable.Select(x => x).ToList().Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.DisplayName.ToString()
});
ViewBag.YourList = AddDefaultOption(ViewBag.YourList, "Select One...", "null", true);
And finally at the View you could display a dropdown, combobox just like this
<div class="editor-label">
Your Label
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ForeignKey, (IEnumerable<SelectListItem>)ViewBag.YourList)
</div>
I wanted to set the default value to whatever was passed in as a Url Parameter called SiteType:
<div class="form-group">
#Html.LabelFor(model => model.Type, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Type, ChangeOrderSite.SiteTypeNames.Select(s => new SelectListItem { Text = s.Value, Value = s.Key.ToString(), Selected = s.Key.ToString() == Request["SiteType"] }), new { #class = "control-label col-md-2" })
#Html.ValidationMessageFor(model => model.Type)
</div>
</div>
My drop down is a list of Site Types.
I like the following method:
#Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.Items, "Id", "Name"), new SelectListItem() { Text = "None", Value = "", Selected = true }.Text, new { #class = "form-control search-select-input btn btn-block btn-outline-secondary dropdown-toggle p-1" })
Where Items is an IEnumerable of type you want to display in the dropdown. And you can change out whatever bootstrap classes you want in the last parameter.
This way allows you to set a default label and specify the value of the label if needed.

Resources