to set dropdownlist value in view when record is extracted in mvc - asp.net-mvc-3

working with MVC 3.
I have a dropdownlist which populates Gender with value 'M' for text 'Male' and 'F' for text 'Female'.
Now, when I extract record it is not setting the value as per the record's value.
I have following on code in view.
#if(Model != null)
{
#Html.DropDownListFor(model => model.GENDER,
new SelectList(ViewBag.gender, "Value", "key", Model.GENDER))
}
else
{
#Html.DropDownListFor(model => model.GENDER,
new SelectList(ViewBag.gender, "Value", "Key"))
}
The above code means that when page first loads it has no value for gender field as model is empty so just populate list and when person is extracted i.e. when model is not null it populates and set value equal to model.gender. But it is not setting the value. What could be the problem?

Are you passing an NULL object (your model) to your view ? How many places in the view are you going to write #if(Model != null).. . Is that not going to mess up the concept of Clean code. ?
I guess this is how you should do it. You should always pass the model/ Viewmodel to the view no matter it is the firs time (Create Entity) or the Editing time. Some thing like this
public ActionResult Create()
{
CustomerViewModel model=new CustomerViewModel();
return View(model);
}
For Edit action, You fill the Model/ViewModel object filled with data.
public ActionResult Edit(int id)
{
CustomerViewModel model=new CustomerViewModel();
model=CustomerService.GetCustomerFromId(id);
return View(model);
}
and in the View, you use it like this
#model CustomerViewModel
#Html.DropDownListFor(model => model.GENDER,
new SelectList(ViewBag.gender, "Value", "key", Model.GENDER))

Related

finding out the firstrow values of <SelectListItem> in the controller before sending them to view MVC3?

Im binding UsersList to a dropdownlist using a selectlistitem
#Html.DropDownListFor(m => m.UserId, new SelectList(Model.Users, "Value", "Text", Model.UserId))
public List<SelectListItem> Users { get; set; }
Public ActionResult LoadUsers()
{
UserModel usrModel=new UserModel();
usrModel.LoadUsers();
string firstUser=?
return view(usrModel);
}
Im binding UsersList to a dropdownlist using a selectlistitem
my requirement is when the user is sensing the Users to view from controller, i want to find out the value field of the User in first row, i.e before binding to the dropdownlist itself i want to find out who is the first User who will be selected in the dropdownlist when the page first loads

MVC dropdownlist , data not displaying when model is not Ienumerable

I am having a problem passing to the View a Model that contains the dropdown data and the model.
With this code my page loads, but the dropdownlist contains "System.Web.MVC.SelectList" when selected.
Here's my controller code.
public ActionResult Index(string productNameFilter, string productCategoryFilter, String productTypeFilter )
{
var ddl = new Items();
ddl.CategoryddList = itemsRepository.GetItemDdl("Item Categories").Select(c => new SelectListItem
{
Value = c.DropdownID.ToString(),
Text = c.DropdownText
});
ViewBag.CategoryDD = new SelectList(ddl.CategoryddList, "Value", "Text");
var model = itemsRepository.GetItemByName(productNameFilter);
return View(model);
}
Here's my view
#model Ienumerable<Models.items.items>
#Html.DropDownList("productCategoryFilter",
new SelectList(ViewBag.CategoryDD),
"---Select Category---")
Side note - if you use a ViewModel between the View and the Model instead of binding directly to the model, you can put your SelectList on the ViewModel and use #Html.DropdownFor() instead of #Html.Dropdown(). The ViewBag should really be used sparingly.
However back to your original question:
What is "Items()"? in your line
var ddl = new Items();
I'm not sure what good reason you would have NOT to make it enumerable.
I suspect it is not working because you are making a selectlist from a select list twice --
in your code behind you are defining ViewBag.CategoryDD as a SelectList(), and then in your Razor code you are creating a new SelectList() from the existing selectlist. You shouldn't have to do this.
The way I would do this is create a ProductViewModel class that contains your product category list AND your list of products (your current model), and a property for the selected filter.
public class ProductViewModel
{
public IEnumerable<Model.items.items> ProductList {get;set;}
public IEnumerable<SelectListItem> ProductCategoryList {get;set;} //SelectList is an IEnumerable<SelectListItem>
public string SelectedCategory {get;set;}
}
Then on your view the model would be
#model ProductViewModel
#Html.DisplayFor(model => model.SelectedCategory, "---Select Category---")
#Html.DropdownListFor(model => model.SelectedCategory, Model.ProductCatgoryList)

Preselection in a DropDownList

I'm just starting with MVC3 and I have the following situation.
My app's initial sign up page among other controls contains a drop down menu. When the user has completed the form then the form details are saved in a session and they move on to the next step. They may also move back to the original step to re-edit, in which case I need to show the drop down menu with the appropriate value preselected.
My code is as follows:
Controller:
public ActionResult Index()
{
var model = new CompanyDetailsModel();
BindDropDownLists(model);
//IF WE HAVE A SESSION THEN PREFILL THE VALUES
if(MySession.Current.IFA!=null)
model = EditIFAProfileService.returnCompanyDetailSession(MySession.Current.IFA);
return View("CreateCompanyDetails", model);
}
I am getting the expected values from the model, so for example the
value model.Salutation is equal to an integer.
So, armed with that value I would expect to be able to set the preselected value of my dropdownlist as follows:
#Html.DropDownListFor(model => model.SalutationValue, Model.SalutationItems,
"Please Select", new { #tabindex = "1" })
If I do set the model value of SalutationValue to an int then I get an error stating that
ViewData item that has the key is of type 'System.Int32' but must be of type 'IEnumerable'.
Any help would be much appreciated.
Thank you.
Don't use any ViewData if you are working with strongly typed views and view models as it would conflict. Simply set the SalutationValue property to some given value. Here's an example:
public ActionResult Index()
{
var model = new CompanyDetailsModel();
model.SalutationItems = ...
if (MySession.Current.IFA != null)
{
model.SalutationValue = MySession.Current.IFA;
}
return View("CreateCompanyDetails", model);
}

How to post the selected value of a selectlist to the controller using a view model?

This question has been asked in various forms but none of the answers seem to fit my situation. I am simply trying to retrieve the selected value of a dropdown list in my controller.
Here is my code:
ViewModel.cs
public class ViewModel
{
public ViewModel() {}
public ViewModel(Contact contact, IEnumerable<State> states)
{
this.Contact = contact;
this.States = new SelectList(states, "Id", "Name", contact.StateId);
}
public Contact Contact {get;set;}
public SelectList States {get;set;}
}
Controller.cs
[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
_contactService.UpdateContact(viewModel.Contact);
return RedirectToAction("Item", new {id = viewModel.Contact.Id});
}
View.cshtml
<button type="submit" onclick="javascript:document.update.submit()"><span>Update</span></button>//aesthic usage.
#{using (Html.BeginForm("Edit", "Controller", FormMethod.Post, new { name = "update" }))
{
#Html.HiddenFor(m => m.Contact.Id)
#Html.LabelFor(m => m.Contact.Name, "Name:")
#Html.TextBoxFor(m => m.Contact.Name)
<label for="state">State:</label>
#Html.DropDownList("state", Model.States)
}
}
Everything works as expected except that no values from the dropdownlist are passed in my posted viewModel to the controller. The edit page and all fields load correctly. The dropdowns bind correctly and have their selected values displayed properly. However, when I post I only get a "Contact" object passed to the controller. The "States" SelectList object is null.
I tried mapping a "StateId" property in my viewModel contstructor but that did not work either. What am I doing wrong?
Thanks.
I hate answering my own questions but based on the multiple issues I had coupled with the myriad of answers available I thought I would summarize my findings.
First off thanks for Filip, his answer did not exactly fix my problem but it led me in the right direction. +1
If you are creating a form for viewing and editing that requires a drop down list, here are some suggestions and gotchas. I will start with a list of parameters that I needed to fit my needs.
Strongly typed views in my view are preferable. Minimize magic strings.
View models should contain as little logic and extraneous elements as possible. There only job should be to facilitate a collection of data objects.
The drop down list should display the selected value.
The selected value should map easily back to the view model on form submit.
This may sound like an obvious and easily obtainable list but for someone new to MVC, it is not. I will revise my code from above with comments. Here is what I did.
ViewModel.cs
public class ViewModel
{
public ViewModel() {}
public ViewModel(Contact contact, IList<State> states)
{
//no need to pass in a SelectList or IEnumerable, just what your service or repository spits out
this.Contact = contact;
this.States = states;
}
public Contact Contact {get;set;}
public IList<State> States {get;set;}
}
Controller.cs //nothing really different than above
public ActionResult Edit(int id)
{
var contact = _contactService.GetContactById(id);
var states = _stateService.GetAllStates();
return View(new ViewModel(contact, states));
}
public ActionResult Edit(ViewModel viewModel)
{
_contactService.UpdateContact(viewModel.Contact);
return RedirectToAction("Edit", new {id = viewModel.Contact.Id });
}
View//thanks goes to Artirto at this post
#{using (Html.BeginForm("Edit", "Controller", FormMethod.Post))
{
#Html.HiddenFor(m => m.Contact.Id)
#Html.DropDownListFor(m => m.Contact.StateId, new SelectList(Model.States, "Id", "Name", #Model.Contact.StateId))
<input type="submit" value="Save" />
}
}
Try using #Html.DropDownListFor instead, if "state" is a part of your model you can use it like this:
#Html.DropDownListFor(m => m.Contact.StateId, Model.States, "-- Please select a State --") where m.State holds the selected value.
Also not to confuse the IEnumerable with the Model, I would put that in the ViewBag / ViewData.
It would look something like this instead:
#Html.DropDownListFor(m => m.Contact.StateId, (IEnumerable<string>)ViewBag.States, "-- Please select a State --")
And in your action that returns this view you will need to initialize the State enumerable to the ViewBag.States property.

ActionResult Details needs to resolve FK from List to display Name?

I have a FK in my Details ViewModel and when the View binds to the ViewModel I only get the FK back (expected). The FK is a reference to a simple ID/Name type table. I also have a Strongly typed List in the VM representing that FK-referenced table. I want to do something like
<div class="display-field">#Model.ManufacturersList.Find(x => x.ID == Model.softwaremanufacturerid))</div>
While this will return the the instance I want...I can't figure out how to get the "Name" attribute to display.
Sorry if this is more a Lamda question but thought I'd try all the same
Thanks
If .ManufacturersList.Find(x => x.ID == Model.softwaremanufacturerid) returns what you want, don't do it in the View. The View should only display data, while the model layer should really be doing the searching (.Find)
In your view model, add a string property for ManufacturerName
public string ManufacturerName { get; set; }
In your controller,
MyViewModel vm = new MyViewModel()
{
ManufacturerName = .ManufacturersList
.Find(x => x.ID == theFKAlreadyInTheViewModel)
};
return View(vm);
Then in your view,
#Model.ManufacturerName
OR, more simply, you could use the ViewBag
ViewBag.ManufacturerName = YourManufacturersList
.Find(x => x.ID == theFKAlreadyInTheViewModel);
Then in your View,
#ViewBag.ManufacturerName

Resources