In my application I have associated my UserId to a table in my database. I need that when I create a new item I can choose the user name from a dropdownlist. And 'possible to do this with the element viewbag?
#Html.EditorFor(model => model.UserId)
I use default membership provider so I can't use Entity Framework for this problem
EDIT
EDIT 2
This is my action create:
[HttpPost]
public ActionResult Create(Employe employe)
{
var users = Roles.GetUsersInRole("Admin");
SelectList list = new SelectList(users);
ViewBag.Users = list;
if (ModelState.IsValid)
{
**employe.EmployeID = users;**
db.Employes.Add(employe);
db.SaveChanges();
}
This does not work. The error is:
Cannot implicitly convert type 'string[]' to 'string'
My model for Employee
public class Employee
{
[Key]
public int EmployeID { get; set; }
public Guid UserId { get; set; }
public string Name { get; set; }
[ForeignKey("UserId")]
public virtual MembershipUser User
{
get
{
return Membership.GetUser(this.Name); //Changed this to Name
}
}
}
}
View:
#Html.DropDownList("Users", ViewBag.Users as SelectList);
My result in UserId field isn't a UserId but this 000000-000000-0000000-00000
How to set a list of users as a SelectItem in the ViewBack
Yes, you should be able to do this by passing your collection to the ViewBag and then create you dropdown from it:
In your controller
var users = Roles.GetUsersInRole("Admin");
SelectList list = new SelectList(users);
ViewBag.Users = list;
In your View (If you're using Razor)
#Html.DropDownList("Users", ViewBag.Users as SelectList);
Read more about SelectListItem here:
http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.aspx
Also check out:
How can I get this ASP.NET MVC SelectList to work?
Problem with ASP.Net MVC SelectLIst and List<SelectListItems>
Question changed to something more. Here is my idea to solve the issue:
Controller:
public ActionResult Mirko() {
List<SelectListItem> items = new List<SelectListItem>();
foreach (string userName in Roles.GetUsersInRole("Admin")) {
var user = Membership.GetUser(userName);
SelectListItem li = new SelectListItem {
Value = user.ProviderUserKey.ToString(),
Text = user.UserName,
};
items.Add(li);
}
items.Add(new SelectListItem { Text = "Please Select...", Value = "na" , Selected = true});
ViewBag.Users = items;
return View();
}
[HttpPost]
public ActionResult Mirko(Employee employee) {
if(IsValideEmployee(employee)) {
/*Only used to show that user was retrieved*/
TempData["message"] = "Saved Employee";
TempData["user"] = employee.User;
/* employeeRepository.Save(employee) */
/* Redirect to where you want to go */
return RedirectToAction("Mirko", "Home");
}
return View(employee);
}
private bool IsValideEmployee(Employee emp) {
if (emp.Name == "na")
ModelState.AddModelError("UserId", "You must select a user!");
/*Do some validation here*/
//ModelState.Add("Name", "You must set the user name!")
return ModelState.IsValid;
}
View
#model StackOverFlowExample.Models.Employee
#{
MembershipUser user = null;
ViewBag.Title = "Mirko Example";
var users = ViewBag.Users as IEnumerable<SelectListItem>;
}
#if (TempData["message"] != null) {
user = TempData["user"] as MembershipUser;
<h3>#TempData["message"]</h3>
<div>
<span>You selected #user.UserName</span>
<ul>
<li>Email: #user.Email</li>
<li>Last Logged In: #user.LastLoginDate.ToString("d")</li>
<li>Online: #user.IsOnline</li>
</ul>
</div>
}
#using (#Html.BeginForm()) {
<label for="UserId">Associate Employee To User:</label>
#Html.DropDownListFor(m => m.UserId, #users)
#Html.HiddenFor(m => m.Name)
<input type="submit" value="Save" id="save-employee"/>
}
<div id="status" style="display:none;"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#UserId").change(function () {
//Set value of name
$("#Name").val($(this).children("option:selected").text());
});
$("#save-employee").click(function (e) {
var value = $("#Name").val();
if (value == "" || value == "na") {
e.preventDefault();
$("#status").html("<h3>You must select a user!</h3>").toggle();
}
});
});
</script>
Related
I am following this tutorial which works very fine. But the problem is that it only provides key and without it own value (As shown in the picture below). How to include values to each of these keys?
Inspected Elements (Picture)
Model
[Required( ErrorMessage = "Selection is a MUST" )]
public string SelectedItem { get; set; }
private List<string> _items;
public List<string> Items
{
get
{
_items = new List<string>();
_items.Add("One");
_items.Add("Two");
_items.Add("Three");
return _items;
}
}
Controller
public class HomeController : Controller
{
//Render Action
[HttpGet]
public ViewResult Index()
{
DropdownListModel model = new DropdownListModel();
return View(model);
}
//Process Action
[HttpPost]
public ViewResult Index(DropdownListModel model)
{
//TODO: Validate using if(ModelState.IsValid) and process information
return View(model);
}
}
View
<div>
<!--Render the DropDownListmodel -->
#using (Html.BeginForm())
{
<p>#Html.ValidationSummary()</p>
<p>Select an Item : #Html.DropDownListFor(x => x.SelectedItem, new SelectList(Model.Items), "--Choose any Item--" )</p>
<input type="submit" value="Submit" />
}
<!-- Display Selected Item -->
#if (!String.IsNullOrWhiteSpace(Model.SelectedItem))
{
<span>Selected Item : #Model.SelectedItem</span>
}
</div>
What I Attempted
I replaced the codes in models with the code below. But I have error saying Models.KeyValueModel: : EntityType 'KeyValueModel' has no key defined. Define the key for this EntityType.
KeyValueModels: EntityType: EntitySet 'KeyValueModels' is based on type 'KeyValueModel' that has no keys defined.
public List<KeyValueModel> Items
{
get
{
List<KeyValueModel> item = new List<KeyValueModel>();
var n = new KeyValueModel();
n.Key = "1";
n.Value = "One";
item.Add(n);
n = new KeyValueModel();
n.Key = "2";
n.Value = "Second";
item.Add(n);
n = new KeyValueModel();
n.Key = "3";
n.Value = "Three";
item.Add(n);
return item;
}
}
You need to specify on your HttpGet request your Key Value pair like this one:
DropdownListModel model = new DropdownListModel();
model.ItemList = new List<SelectListItem>()
{
new SelectListItem { Text = "One", Value = "1" },
new SelectListItem { Text = "Two", Value = "2" }
};
Then on your model, add this:
public IEnumerable<SelectListItem> ItemList { get; set; }
And on your View:
#Html.DropDownListFor(x => x.SelectedItem, Model.Items, "--Choose any Item--" )
add the Model as:
public string nameofdropdown{ get; set; }
public IEnumerable<SelectListItem> listyouwanttodisplay{ get; set; }
In get method:
Model model=new Model;
List<SelectListItem> cd = Get() //call here----
var additionaldata= new SelectListItem()
{
Value = null,
Text = "--- place holder---"
};
cd.Insert(0, additionaldata);
model.listyouwanttodisplay=cd;
return View (model);
In View:
<div>
#Html.DropDownListFor(model => model.nameofdropdown, new
SelectList(Model.listyouwanttodisplay, "Value","Text"),htmlAttributes: new { #class = "form-control" })
</div>
I am trying to pull the data from a table stored in SQL 2008 into my MVC4
In My Controller :
public ActionResult Test()
{
SurveyEntities survey = new SurveyEntities();
var doctorList = survey.Doctors.ToList();
return View(doctorList);
}
and in my View:
#model IEnumerable<Survey.DataAccess.Doctor>
#{
ViewBag.Title = "Test";
}
<h2>Test</h2>
#using (Html.BeginForm("Test", "Home", FormMethod.Post))
{
#Html.DropDownListFor(m => m.)
}
But I am not able to access the field name in m, say for eg., the doctor's name, to bind it to the dropdownlist.
Where am i going wrong ?
If you dont need to bind to the result value you can also use Html.DropDownList('name', new SelectList(Model)) If you have to use DropDownListFor you would have to change your model and add a property to bind the select result like Html.DropDownListFor(m=>m.DoctorId, new SelectList(Model.Doctors).....
Normally, you want to use ViewModel, so that you can retrieve the selected doctorId when the form is posted back to server.
For example,
Model
public class SurveyModel
{
public string SelectedDoctorId { get; set; }
public IList<SelectListItem> AvailableDoctors { get; set; }
public SurveyModel()
{
AvailableDoctors = new List<SelectListItem>();
}
}
View
#model DemoMvc.Models.SurveyModel
#using (Html.BeginForm("Index", "Home"))
{
#Html.DropDownListFor(m => m.SelectedDoctorId, Model.AvailableDoctors)
<input type="submit" value="Submit" />
}
Controller
public ActionResult Index()
{
var model = new SurveyModel
{
AvailableDoctors = GetDoctorListItems()
};
return View(model);
}
[HttpPost]
public ActionResult Index(SurveyModel model)
{
if (ModelState.IsValid)
{
var doctorId = model.SelectedDoctorId;
// Do something
return View("Success");
}
// If we got this far, something failed, redisplay form
// Fill AvailableDoctors again; otherwise, DropDownList will be blank.
model.AvailableDoctors = GetDoctorListItems();
return View(model);
}
private IList<SelectListItem> GetDoctorListItems()
{
/*
SurveyEntities survey = new SurveyEntities();
return survey.Doctors
.Select(d => new SelectListItem {Text = d, Value = d.ToString()})
.ToList();
*/
// Simulate doctors return from database.
return new List<SelectListItem>
{
new SelectListItem {Text = "John Doe", Value = "1"},
new SelectListItem {Text = "Eric Newton", Value = "2"}
};
}
you can put this code in the Test method:
> ViewData["doctors"] = new SelectList(doctorList,"value", "text");
and then in a view:
#using (Html.BeginForm("Test", "Home", FormMethod.Post))
{
#Html.DropDownList("name", ViewData["doctors"] as SelectList)
input type="submit" value="Submit" />
}
I know this might be a lot of code to look at it, but it seemed like it was necessary to share it. Thanks in advance for reading!
I am building an application starting with the ASP.NET MVC 5 default template. I want to add a checkbox list of Identity's ApplicationRoles to the Register action of the Account controller.
So, rather than just collect the first and last names, email, phone number, etc., I also want to supply a checkbox list of roles in the database.
I've added this to the RegisterViewModel (in AccountViewModels.cs):
[Required]
[Display(Name = "Roles List")]
public IEnumerable<SelectListItem> RolesList { get; set; }
I changed the Account controller's HttpGet Register action from this:
// GET: /Account/Register
public ActionResult Register()
{
return View();
}
to this:
// GET: /Account/Register
[HttpGet]
public ActionResult Register()
{
//Populate the roles checkbox list for the view
RegisterViewModel model = new RegisterViewModel
{
RolesList = RoleManager.Roles.OrderBy(r => r.Name).ToList().Select(r => new SelectListItem()
{
Text = r.Name,
Value = r.Name,
Disabled = (r.Name == "Admin" && !User.IsInRole("Admin"))
})
};
return View(model);
}
Finally, I updated the Account controller's HttpPost Register action to this:
// POST: /Account/Register
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model, params string[] rolesSelectedOnView)
{
if (ModelState.IsValid)
{
rolesSelectedOnView = rolesSelectedOnView ?? new string[] { };
var user = new ApplicationUser { FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, UserName = model.Email, Email = model.Email};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var rolesAddResult = await UserManager.AddToRolesAsync(user.Id, rolesSelectedOnView.ToString());
if (!rolesAddResult.Succeeded)
{
ModelState.AddModelError("", rolesAddResult.Errors.First());
AddErrors(rolesAddResult);
return View(model);
}
string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
ViewBag.Message = "A confirmation email has been sent to the address you specified. Please have "
+ "the person check their email and confirm their account. The account must be confirmed "
+ "from the confirmation email before they can log in.";
return View("Info");
//return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
The Register view looks (in part) like this:
#model MngiReferrals.Models.RegisterViewModel
#{
ViewBag.Title = "Register";
}
<h2>#ViewBag.Title.</h2>
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
...removed...
<div class="form-group">
#Html.Label("Roles", new { #class = "col-md-offset-2 col-md-10" })
<span class="col-md-offset-2 col-md-10">
#foreach (var item in Model.RolesList)
{
<input type="checkbox" name="RolesList" value="#item.Value" class="checkbox-inline" />
#Html.Label(item.Value, new {#class = "control-label"})
<br />
}
</span>
</div>
This allows the Register view to render with the normal fields and the list of roles in the database. However, when I submit the form, it doesn't try to validate the roles list (even though I've marked it as [Required] in the view model. Furthermore, it returns me to the Register form with the fields filled in, but then the checkbox list of roles is no longer on the form.
Finally, if I try to submit the form again, it returns this error from the view:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Line 51: #Html.Label("Roles", new { #class = "col-md-offset-2 col-md-10" })
Line 52: <span class="col-md-offset-2 col-md-10">
Line 53: #foreach (var item in Model.RolesList)
Line 54: {
Line 55: <input type="checkbox" name="RolesList" value="#item.Value" class="checkbox-inline" />
After making these changes, the user is no longer registered in the database, so I'm not sure I'm even ever making it to the HttpPost Register action.
I would appreciate it if someone could help me fill in the blanks on this problem. Thank you in advance!
UPDATE #1
I updated my code based on a previous answer by #StephenMuecke (see his comment below for the link). I am close, but it looks like I am not correctly capturing the selected checkbox values.
Here is what this looks like now.
RegisterViewModel (in AccountViewModels.cs):
public class RegisterViewModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
...more properties...
[Required]
[Display(Name = "Roles List")]
public IEnumerable<SelectListItem> RolesList { get; set; }
public RegisterViewModel()
{
RolesList = new List<ApplicationRoleRegisterViewModel>();
}
}
ApplicationRoleRegisterViewModel (new View Model for the ApplicationRoles)
public class ApplicationRoleRegisterViewModel
{
[Required]
public string Name { get; set; }
public bool IsSelected { get; set; }
public bool IsDisabled { get; set; }
}
HttpGet Account Register action:
// GET: /Account/Register
[HttpGet]
public ActionResult Register()
{
//Populate the roles checkbox list for the view
var model = new RegisterViewModel { RolesList = new List<ApplicationRoleRegisterViewModel>() };
var roles = RoleManager.Roles.OrderBy(r => r.Name);
foreach (var role in roles)
{
var roleVm = new ApplicationRoleRegisterViewModel
{
Name = role.Name,
IsSelected = false, // Since this is for a user that does not yet exist, this would initially be deselected.
IsDisabled = role.Name == "Admin" && !User.IsInRole("Admin")
};
model.RolesList.Add(roleVm);
};
return View(model);
}
HttpPost Account Register action:
// POST: /Account/Register
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, UserName = model.Email, Email = model.Email};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
//populate the roles checkbox list
var rolesSelectedOnView = model.RolesList.ToList();
foreach (var role in rolesSelectedOnView)
{
var roleVm = new ApplicationRoleRegisterViewModel
{
Name = role.Name,
IsSelected = role.IsSelected,
IsDisabled = role.IsDisabled
};
model.RolesList.Add(roleVm);
};
var rolesAddResult = await UserManager.AddToRolesAsync(user.Id, rolesSelectedOnView.Select(r => r.Name).ToArray());
if (!rolesAddResult.Succeeded)
{
ModelState.AddModelError("", rolesAddResult.Errors.First());
AddErrors(rolesAddResult);
return View(model);
}
string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
// Uncomment to debug locally
// TempData["ViewBagLink"] = callbackUrl;
ViewBag.Message = "A confirmation email has been sent to the address you specified. Please have "
+ "the person check their email and confirm their account. The account must be confirmed "
+ "from the confirmation email before they can log in.";
return View("Info");
//return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
Register View (uses RegisterViewModel):
<div class="form-group">
#Html.Label("Roles", new { #class = "col-md-offset-2 col-md-10" })
<span class="col-md-offset-2 col-md-10">
#for (var i = 0; i < Model.RolesList.Count; i++)
{
#Html.HiddenFor(m => m.RolesList[i].Name)
#Html.CheckBoxFor(m => m.RolesList[i].IsSelected)
#Html.LabelFor(m => m.RolesList[i].IsSelected, Model.RolesList[i].Name)
<br />
}
</span>
</div>
I am trying to pass the Model data from a View (and PartialView within the View) back to the Controller upon HttpPost. (Adapted from Pass SelectedValue of DropDownList in Html.BeginForm() in ASP.NEt MVC 3)
Why? I want to show a list of assets each with a DropDownList and number of options. Upon submission of form to read the selected items from DropDownList.
My 2 (simplified) models:
public class Booking
{
public int BookingID { get; set; }
public int StoreID { get; set; }
...
public IEnumerable<AssetShort> Assets { get; set; }
}
and
public class AssetShort
{
public int AssetID { get; set; }
....
public int SelectedAction { get; set; }
public IEnumerable<SelectListItem> ActionList { get; set; }
}
In my Booking Controller > Create I build the List:
public ActionResult Booking(int id)
{
// get myBag which contains a List<Asset>
// booking corresponds to 'id'
var myAssets = new List<AssetShort>();
foreach (var a in myBag.Assets)
{
var b = new AssetShort();
b.AssetID = a.ID;
b.SelectedAction = 0;
b.ActionList = new[]
{
new SelectListItem { Selected = true, Value = "0", Text = "Select..."},
new SelectListItem { Selected = false, Value = "1", Text = "Add"},
new SelectListItem { Selected = false, Value = "2", Text = "Remove"},
new SelectListItem { Selected = false, Value = "3", Text = "Relocate"},
new SelectListItem { Selected = false, Value = "4", Text = "Upgrade"},
new SelectListItem { Selected = false, Value = "5", Text = "Downgrade"}
};
myAssets.Add(b);
};
var model = new BookingRequirementsViewModel
{
BookingID = booking.ID,
StoreID = booking.StoreID,
Assets = myAssets.ToList(),
};
return View(model);
My View:
#model uatlab.ViewModels.BookingRequirementsViewModel
#{
ViewBag.Title = "Booking step 2";
}
<h4>Your booking ref. #Model.BookingID</h4>
#using (Html.BeginForm("Booking2", "Booking", FormMethod.Post))
{
<fieldset>
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.StoreID)
#Html.Partial("_Assets", Model.StoreAssets)
<input type="submit" value="Cancel" class="btn btn-default" />
<input type="submit" value="Next" class="btn btn-default" />
</fieldset>
}
The Partial View includes
#foreach (var item in Model)
{
<tr>
<td>#item.Name</td>
<td>#item.Number</td>
<td>#Html.DropDownListFor(modelItem=>item.SelectedAction, item.ActionList)</td>
</tr>
}
So, all this works fine in the browser and I can select dropdowns for each asset listed but when I submit the only value posted back is the StoreID as it is in a "HiddenFor".
The booking2 controller has the model for a parameter:
public ActionResult Booking2(BookingRequirementsViewModel model)
{
//loop through model.Assets and display SelectedActions
}
Let me make it clear what the problems is - in Booking2 controller the Model is null when viewed in Debug mode and I get error "Object reference not set to an instance of an object."
Any ideas please how to pass back the Model to controller from view?
Regards
Craig
You need to create an EditorTemplate for AssetShort. I also suggest moving ActionList to the BookingRequirementsViewModel so your not regenerating a new SelectList for each AssetShort
The models you have posted aren't making sense. Your controller has var model = new BookingRequirementsViewModel { ..., Assets = myAssets.ToList() }; but in the view you refer to #Html.Partial("_Assets", Model.StoreAssets)? Are these 2 different properties. I will assume that StoreAssets is IEnumerable<AssetShort>
/Views/Shared/EditorTemplates/AssetShort.cshtml
#model AssetShort
<tr>
<td>#Html.DispayFor(m => m.Name)</td>
....
<td>
#Html.DropDownListFor(m => m.SelectedAction, (IEnumerable<SelectListItem>)ViewData["actionList"], "--Please select--")
#Html.ValidationMessageFor(m => m.SelectedAction)
</td>
</tr>
In the main view
#model uatlab.ViewModels.BookingRequirementsViewModel
....
#using (Html.BeginForm()) // Not sure why you post to a method with a different name
{
....
#Html.HiddenFor(m => m.StoreID)
#Html.EditorFor(m => m.StoreAssets, new { actionList = Model.ActionList })
....
}
In the controller
public ActionResult Booking(int id)
{
....
var model = new BookingRequirementsViewModel
{
BookingID = booking.ID,
StoreID = booking.StoreID,
Assets = myBag.Assets.Select(a => new AssetShort()
{
AssetID = a.ID,
SelectedAction = a.SelectedAction, // assign this if you want a selected option, otherwise the "--Please select--" option will be selected
....
})
};
ConfigureViewModel(model); // Assign select list
return View(model);
}
And a separate method to generate the SelectList because it needs to be called in the GET method and again in the POST method if you return the view. Note use the overload of DropDownListFor() to generate the option label (null value) as above, and there is no point setting the Selected property (the value of SelectedAction determines what is selected, not this)
private ConfigureViewModel(BookingRequirementsViewModel model)
{
model.ActionList = new[]
{
new SelectListItem { Value = "1", Text = "Add"},
....
new SelectListItem { Value = "5", Text = "Downgrade"}
};
}
and the POST
public ActionResult Booking(BookingRequirementsViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model); // Re-assign select list
return View(model);
}
// save and redirect
}
I recommend also making SelectedAction nullable with the [Required] attribute so you get client and server side validation
public class AssetShort
{
public int AssetID { get; set; }
....
[Required]
public int? SelectedAction { get; set; }
}
I am designing a simple webpage using MVC3 in asp.net. I prepared a database using Sql Server, and i have attached this database in App_Data. There is a table employee in that database.
i want to get name of employee in a drop down list. so i can select name of employee.
so please suggest me what will be model,view and controller code for accessing employee name in drop down list.
I would start by designing a view model which will hold the data:
public class EmployeeViewModel
{
public string SelectedEmployeeName { get; set; }
public IEnumerable<SelectListItem> Employees { get; set; }
}
then a controller:
public class HomeController: Controller
{
public ActionResult Index()
{
IEnumerable<Employee> employees = GetEmployeesFromDb();
var model = new EmployeeViewModel
{
Employees = employees.Select(x => new SelectListItem
{
Value = x.Name,
Text = x.Name
})
};
return View(model);
}
[HttpPost]
public ActionResult Index(EmployeeViewModel model)
{
return Content("Selected employee name: " + model.SelectedEmployeeName, "text/plain");
}
}
and finally the strongly typed view:
#model EmployeeViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(
x => x.SelectedEmployeeName,
new SelectList(Model.Employees, "Value", "Text")
)
<input type="submit" value="OK" />
}
1) Create a Method to populate the list from DB
2) Set a ViewModel to hold the List and selected value
//MODEL
public List<SelectListItem> CategoriesSelectList()
{
var query = from c in _yourRepository.GetAll()
select c;
List<SelectListItem> obj = new List<SelectListItem>();
foreach (var item in query)
{
var result = new SelectListItem();
result.Text = item.name;
result.Value = item.id.ToString();
obj.Add(result);
}
return obj;
}
//VIEWMODEL
public class ViewModel
{
[DisplayName("Category")]
public int categoryId { get; set; }
public List<SelectListItem> CategoryList()
{
return new Model().CategoriesSelectList();
}
}
//CONTROLLER
public ActionResult Create()
{
//set the id for the VIEWMODEL property, if necesary
var e = new ViewModel();
e.categoryId = 1;//set the selected value
return View(e);
}
//VIEW
<div class="editor-label">
<%: Html.LabelFor(model => model.categoryId) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.categoryId,Model.CategoryList()) %>
<%: Html.ValidationMessageFor(model => model.categoryId) %>
</div>