How to bind a drop down with a model property while containing the list items of that drop down? - asp.net-mvc-4

I am stuck in a problem, I have retrieved all the value for a drop down in a view bag and want to display them at run time. I have achieved it by using the following code for the controller
[HttpGet]
public ActionResult Index()
{
var categoryList = new PersonalApp();
SelectList catList = new SelectList(categoryList.GetAffinity().ToList(), "ClientName", "AffinityNum");
ViewBag.categoryList = catList;
return View();
}
and the following code for the view
#using (Html.BeginForm("index", "Home"))
{
#Html.DropDownList("categoryList", "Branch Type")
}
It really works but now I want to bind it with a model now. I have use the following code for this:
#Html.DropDownListFor(model=>model.AffinityNum, "categoryList", "BranchType")
But it gives me an error as CategoryList cannot be used as a parameter with the above code. How will I get this resolved as I can have all the values of a dropdown in the categorylist and I can bind it with a model property affinityNum with it as well.
Thanks

Your model should have an IEnumerable<SelectListItem> property that will hold the values:
public class PersonalApp
{
public string AffinityNum { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
}
that you will populate in your controller action and pass to the view:
[HttpGet]
public ActionResult Index()
{
var model = new PersonalApp();
var categories = categoryList.GetAffinity().ToList();
SelectList catList = new SelectList(categories, "ClientName", "AffinityNum");
model.CategoryList = catList;
return View(model);
}
and finally in your strongly typed view you will use this property to bind the dropdown list to:
#model PersonalApp
...
#Html.DropDownListFor(x => x.AffinityNum, Model.CategoryList, "BranchType")

Please try;
#Html.DropDownListFor(model=>model.AffinityNum, (SelectList)ViewBag.categoryList)

Related

Getting model to viewmodel easily

I have a view-model like this:
public class U1MyProfile1ViewModel : U1Profile
{
public List<SelectListItem> CountryList { get; set; }
}
Thinking that I want the model accessible to the view, plus a some extra fields that aren't really part of the model, such as a drop down list of countries.
Then in the controller I try to "pass the model over to the view-model"
var myProfile = await _mainDbContext.U1Profiles
.AsNoTracking()
.FirstOrDefaultAsync(i => i.SiteUserId == mySiteUserId);
U1MyProfile1ViewModel myProfileViewModel = (U1MyProfile1ViewModel)myProfile;
this compiles, but I get a runtime error of:
InvalidCastException: Unable to cast object of type 'WebApp.Models.U1Profile' to type 'WebApp.ViewModels.U1MyProfile1ViewModel'.
Any ideas on how to do this easily?
Something simpler than assigning the model to the view-model field by field.
Set your View model like follow:
View modal
public class U1MyProfile1ViewModel
{
public List<SelectListItem> CountryList { get; set; }
public U1Profile U1Profile{get;set;}
public string othervariable{get;set;}
}
Controller
var myProfile = await _mainDbContext.U1Profiles
.AsNoTracking()
.FirstOrDefaultAsync(i => i.SiteUserId == mySiteUserId);
U1MyProfile1ViewModel myProfileViewModel = new U1MyProfile1ViewModel;
U1MyProfile1ViewModel.U1Profile=myProfile;
U1MyProfile1ViewModel.CountryList=yourcountrylist;
And finally just passed your viewmodal to View and you get your result.
For better understanding just see below link:
Link1
Link2

How HtmlHelper know data is on the ViewBag?

I was watching a tutorial about HtmlHelper for DropDown https://www.youtube.com/watch?v=79aYSOcmpV8
Around min 8, he is reading the db to replace some hardcode values.
To pass list of Departments from the controller, store them in "ViewBag"
public ActionResult Index()
{
// Connect to the database
SampleDBContext db = new SampleDBContext();
// Retrieve departments, and build SelectList
ViewBag.Departments = new SelectList(db.Departments, "Id", "Name");
return View();
}
Last step.
Now in the "Index" view, access Departments list from "ViewBag"
#Html.DropDownList("Departments", "Select Department")
I dont see anything like strong type model on the view.
So how the Helper know Departments refers to a value in the ViewBag?
When you add a value to ViewBag, it is also added to the ViewData property of ViewContext when the view is generated. The DropDownList() overload that your using in equivalent to passing a null SelectList in
#Html.DropDownList("Departments", null, "Select Department")
in which case, internally, the helper searches the ViewData property to find a matching key which is an IEnumerable<SelectListItem> (which "Departments" is). You can see the relevant code in the private static MvcHtmlString SelectInternal() method of the source code
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = htmlHelper.GetSelectData(name);
....
}
Note that the example in the tutorial is a poor approach, using 'magic' strings and requiring you to access the value in the POST method using Request.Form["Departments"]. A far better approach is to use a view model and strongly bind to your view model, for example
public class MyViewModel
{
public int SelectedDepartment { get; set; }
public IEnumerable<SelectListItem> DepartmentList { get; set; }
...
}
and the GET method would be
public ActionResult Create()
{
MyViewModel model = new MyViewModel
{
DepartmentList = new SelectList(db.Departments, "Id", "Name");
};
return View(model);
}
and in the view
#model MyViewModel
....
#Html.DropDownListFor(m => m.SelectedDepartment, Model.DepartmentList, "Select Department")
and post the form back to
[HttpPost]
public ActionResult Create(MyViewModel model)

loading dropdown list with data from table in mvc4

I have 3 models and corresponding tables (EnquiryModel, EmployeeModel, RegionModel).
I want to populate a dropdown list in both the 'create' views of Enquiry and Employee.
That dropdown list should be filled with the data from the 'Region_Name' field in the RegionModel Table.
How can I do this?
I have RegionModel:
namespace MvcConQuery.Models
{
[Table("Region_Details")]
public class RegionModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int32 Region_id { get; set; }
public string Region { get; set; }
}
}
And also I have EmployeeModel and EnquiryModel, I give the following code in controller of these models:
public ActionResult Create()
{
IEnumerable<SelectListItem> abc = new SelectList(db.Regions, "Region_id", "Region");
ViewBag.regions = abc;
return View();
}
I give this code in Create View:
#Html.DropDownList("regions","select")
But I got the error:
There is no ViewData item of type 'IEnumerable' that has the key 'regions'.
Please help me to code the Create()function in controller and the Create View.
Try like this,
DATAEntities _context = new DATAEntities ();
var List = (from r in _context.Registrations select r).ToList();
ViewBag.CustomerName = new SelectList(List, "Region_id", "Region");
View
#Html.DropDownList("regions", (SelectList)ViewBag.CustomerName, "--Select--")
If you have any concerned let me know.

Trying to use DropDownListFor with ASP.Net. Why is this erroring out?

I have a simple model
public class MyModel
{
public string Month{ get; set;}
public IEnumerable<SelectListItem> Months
{
get
{
return new[] { new SelectListItem{ Text="Jan",Value="1" } };
}
}
}
I would like to display this on a page using DropDownListFor like this
#model ViewModels.MyModel
#Html.DropDownListFor(m=>m.Month, new SelectList(Model.Months,"Text","Value"))
When I build and run this I get and error "Object reference not set to an instance of an object."
If I have a property in my class that is a simple string I can use LabelFor(m=>m.TestString) and it displays that correctly so I know the model exists.
What am I missing?
TIA
Your types are are not matching. In your model you need to do the following:
public SelectList Months
{
get
{
var monthNames = DateTimeFormatInfo.CurrentInfo.MonthNames.Take(12).ToList();
return new SelectList(monthNames.Select(m => new {Id = monthNames.IndexOf(m) + 1, Name = m}).ToList(), "Id", "Name");
}
}
then in your view all you need is:
#Html.DropDownListFor(m => m.Month, Model.Months)
Also make sure your model is instantiated and not null.
it should work . m=>m.Month
and
on controller
MyModel model=new MyModel();
return View(model);

What is the best way to create dropdownlists in MVC 4?

I want to know,What is a best way to create dropdownlists in MVC 4?
With ViewBag or another approach?
I would argue that since the items are variable values within your view that they belong in the View Model. The View Model is not necessarily just for items coming back out of the View.
Model:
public class SomethingModel
{
public IEnumerable<SelectListItem> DropDownItems { get; set; }
public String MySelection { get; set; }
public SomethingModel()
{
DropDownItems = new List<SelectListItem>();
}
}
Controller:
public ActionResult DoSomething()
{
var model = new SomethingModel();
model.DropDownItems.Add(new SelectListItem { Text = "MyText", Value = "1" });
return View(model)
}
View:
#Html.DropDownListFor(m => m.MySelection, Model.DropDownItems)
Populate this in the controller or wherever else is appropriate for the scenario.
Alternatively, for more flexibility, switch public IEnumerable<SelectListItem> for public IEnumerable<MyCustomClass> and then do:
#Html.DropDownFor(m => m.MySelection,
new SelectList(Model.DropDownItems, "KeyProperty", "ValueProperty")
In this case, you will also, of course, have to modify your controller action to populate model.DropDownItems with instances of MyCustomClass instead.