How to Bind dropdown from anonymous class values - asp.net-mvc-3

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)

Related

Setting the default value of multiple dropdown lists on page load

I have a model,
public class Customer
{
public string Name { get; set;}
public string CountryCode { get; set;}
}
In the controller
var model = new List<Customer>
{
new Customer { Name = "foo", CountryCode = "US"},
new Customer { Name = "bar", CountryCode = "UK",
};
return PartialView("_Edit", model);
An extension method for displaying all countries:-
public class CountryList
{
public static IEnumerable<SelectListItem> CountrySelectList
{
get
{
var list = new List<SelectListItem>()
{
new SelectListItem { Value = "US", Text="US" },
new SelectListItem { Value = "UK", Text="UK" },
};
return list;
}
}
}
In the PartialView
#model List<Customer>
#Html.DropDownListFor(model => model[i].CountryCode, CountryList.CountrySelectList, "Select Country Type")
But the drop down doesn't select each customer's country code? Any thoughts?
PS: It is using model[i] => which is of type Customer, for simplicity i had removed the forloop before rendering the html tags.
#using(Html.BeginForm())
{
for(int i = 0; i < Model.Count(); i++)
{
#Html.TextBoxFor(model => model[i].Name)
#Html.DropDownListFor..........
}
}
Because your CoutryList helper does returns a list of SelectListItems that all have Selected property set to False (which is default).
I would rewrite your helper method as follows:
public static IEnumerable<SelectListItem> CountrySelectList(string selectedCountryCode)
{
get
{
var list = new List<SelectListItem>()
{
new SelectListItem { Value = "US", Text="US" },
new SelectListItem { Value = "UK", Text="UK" },
};
var selectedListItem = list.FirstOrDefault(t=>t.Value== selectedCountryCode);
if(selectedListItem!=null)
selectedListItem.Selected=true;
return list;
}
}
In view:
#Html.DropDownListFor(model => model[i].Customer, CountryList.CountrySelectList(model[i].Customer.CountryCode), "Select Country Type")

How to use dropdownlistfor in mvc3 razor with model

I want to use below property in my view with dropdownbox.
How could I ?
I have tried so many ways but
Please help
public IEnumerable<SelectListItem> Topic
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "Science", Selected=true },
new SelectListItem { Value = "2", Text = "History" },
new SelectListItem { Value = "3", Text = "Physics" },
};
}
}
You have not added your view code.
Basically you need to add a #model to your view like this:
#model MySampleApplication.Models.ModelName
And then in your view you should be accessing like this :
#Html.DropdownListFor(m=>m.Topic, Model.Topic)
DropDownListFor with ASP.NET MVC from Scott Allen
Hope it helps
EDIT
Say you have your model class like this:
public class MyModel
{
public IEnumerable<SelectListItem> Topic
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "Science", Selected=true },
new SelectListItem { Value = "2", Text = "History" },
new SelectListItem { Value = "3", Text = "Physics" },
};
}
}
}
Try like this:
public ActionResult Index()
{
MyModel model=new MyModel();
return View(model);
}
Try this
Model
public SelectList Topic
{
get
{
return new SelectList(
new List<SelectListItem> {
new SelectListItem { Value = "1", Text = "Science", Selected = true },
new SelectListItem { Value = "2", Text = "History" },
new SelectListItem { Value = "3", Text = "Physics" }
},"Value","Text"
);
}
}
public int selectedType {get;set;}
View
#Html.DropDownListFor(model => model.selectedType , Model.Topic)

Can't pass parameter id in actionLink

Can't understand where the problem... My rout values is :
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
And i try to pass parameter id :
#Html.ActionLink(app.Name, "SingleAppEdit", "Admin", new { id = app.Id }, null)
To my action in Controller "Admin":
public ActionResult SingleAppEdit(string appId)
{
var positions = new List<SelectListItem>
{
new SelectListItem() {Text = "Top", Value = "Top"},
new SelectListItem() {Text = "Bottom", Value = "Bottom"},
new SelectListItem() {Text = "None", Value = "None"}
};
ViewData["PositionsList"] = new SelectList(positions, "Value", "Text");
var app = Apps.FirstOrDefault(a => a.Id == Convert.ToInt32(appId));
return View(app);
}
I get null in controller. Can anybody help?
Your method parameter name is appId. But you are trying to pass a parameter named id.
Solution : Change your parameter name to match with the method definition.
#Html.ActionLink(app.Name, "SingleAppEdit", "Admin",
new { appId= app.Id }, null)
Change appID in controller to just ID like this:
public ActionResult SingleAppEdit(string id)
{
var positions = new List<SelectListItem>
{
new SelectListItem() {Text = "Top", Value = "Top"},
new SelectListItem() {Text = "Bottom", Value = "Bottom"},
new SelectListItem() {Text = "None", Value = "None"}
};
ViewData["PositionsList"] = new SelectList(positions, "Value", "Text");
var app = Apps.FirstOrDefault(a => a.Id == Convert.ToInt32(id));
return View(app);
}

Avoid duplicate entries in List<SelectListItem>

How can I check that List< SelectListItem> doesn't contain or insert any duplicates in Mvc3. I have tried with !Contains
Thanks
Try this:
var list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "Some Text", Value = "Some Value" });
list.Add(new SelectListItem { Text = "Other Text", Value = "Other Value" });
var selectListItem = new SelectListItem { Text = "Some Text", Value = "Some Value" };
if(!list.Any(l => l.Value == selectListItem.Value)
{
list.Add(selectListItem);
}
.Contains() compares if the object reference, not the Value property
var list = new List<SelectListItem>();
var selectListItem = new SelectListItem { Text = "Some Text", Value = "Some Value" };
if(list.FirstOrDefault(t => t.Value != selectListItem.Value) == null)
{
list.Add(selectListItem);
}

How to walk through a SelectListItem Array with Linq - techniques?

Linq – Newbie question:
string[] grades = { "2", "5", "1", "7", "4", "8", "6", "0", "9", "3" };
List<SelectListItem> xValues = new List<SelectListItem>()
{ new SelectListItem
{ Selected = true,
Text = "Select...",
Value = "Select...",
}
};
for (int a = 0; a < 10; a++)
{
xValues.Add(new SelectListItem
{ Selected = false,
Text = grades[a],
Value = grades[a]
}
);
}
My application works very fine up to this point.
xValues contains now 11 elements. Each element contains a "Selected", "Text" and "Value" property. "Selected" is only in the first element set to "true".
The second elements contains a "2" in "Text" and "Value", the third element contains a “5”, the fourth contains a “1” and so on...
Question:
How to set "Selected" to "true" in that xValue element which contains a "5" in the "Text" (and in the "Value") property?
Note, that not the 6th element contains (necessarily) the searched "5"!
I believe it must be something like that:
for (int i = 0; i < ponyValues.Count(); i++)
{
xValues[i].Selected = false;
if (xValues.First().Value == “5”)
{
xValues[i].Selected = true;
}
}
Of course is ".First()" wrong... but what would be correct?
var five = xValues.FirstOrDefault(x=> x.Value == "5");
if (five != null)
five.Selected = true;
SelectListItem item = xValues.Single(item => item.Value == 5);
item.Selected = true;
Please note that this will throw an exception if there isn't exactly one item with a value of 5.
var xValues = grades.Select(g => new SelectListItem
{
Selected = (g == "5")
Text = g,
Value = g
})
.ToList();
xValues.Insert(0, new SelectListItem
{
Selected = false,
Text = "Select...",
Value = "Select...",
});
Thanks to all!
Finally I do this
var isSelected = xValues.FirstOrDefault(x => x.Selected == true);
var mustBeSelected = xValues.FirstOrDefault(x => x.Value == "5");
if ((isSelected != null) && (mustBeSelected != null))
{
isSelected.Selected = false;
mustBeSelected.Selected = true;
}
because I want also to set "Selected" to "false" for the very first element.
Sorry forgot to you tell this ;-)

Resources