How to retain the ASP.NET dropdownlist selected item - asp.net-mvc

I'm trying to retain the selected value of a dropdownlist once the user change the dropdownlist item but its not working as expected what I wanted is to retain the selected item in the dropdownlist but its it defaulted to the Select Company everytime i select the item from dropdownlist, once the user change it postback the page (i know there is no postback in the MVC)
What I'm doing wrong here?
<div class="form-group">
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #id = "form_dropdown" }))
{
#Html.DropDownListFor(m => m.ListOfCompanies,
new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, "Value", "Text"),
"Select Company", new { #class = "form-control", Name = "sel" })
}
[HttpPost]
public ActionResult Index(string sel)
{
var vModel = new EmployeeViewModel();
vModel = _db.GetEmployee.ToList();
//load list of companies:
var company = _db.LoadComapny.ToList();
IEnumerable<SelectListItem> result = model.Select(b => new SelectListItem
{
Value = b.Value,
Text = b.Text,
Selected = b.Text == sel
}).ToList();
vModel.ListOfCompanies = company;
vModel.SELECTED_COMPANY = sel;
return View(vModel);
}
Model:
public class EmployeeViewModel
{
public IEnumerable<SelectListItem> ListOfCompanies { get; set; }
public string SELECTED_COMPANY { get; set; }
//other props
}

DropdownListFor has 2 important argumnets:
the first one the variable with the index of the selected item (mostly lambda expressions (=>) were used)
the secound one is the SelectList of items availble
#Html.DropDownListFor(m => m.SELECTED_COMPANY,
new SelectList(Model.ListOfCompanies, "Value", "Text"),
"Select Company", new { #class = "form-control", Name = "sel" })

Update it to
#Html.DropDownListFor(m => m.SELECTED_COMPANY,
new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, "Value", "Text"),
"Select Company", new { #class = "form-control", Name = "sel" })

Related

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DiseaseType'

I want to bind data to dropdownlist, select one and save it into database.
I've successfully binded data to dropdownlist but it is giving an error
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DiseaseType'.
on click of save button.
Edit.cshtml code:
<div class="form-group">
#Html.LabelFor(model => model.DiseaseType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DiseaseType, ViewData["Diseases"] as SelectList, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DiseaseType, "", new { #class = "text-danger" })
</div>
</div>
PatientController.cs code:
public ActionResult Edit(int id)
{
List<string> disease = new List<string>();
disease.Add("Select");
disease.Add("Cancer");
disease.Add("Heart");
SelectList Diseases = new SelectList(disease);
ViewBag.Diseases = Diseases;
PatientDBHandle pdb = new PatientDBHandle();
return View(pdb.GetPatient().Find(p => p.ID == id));
}
Patient.cs class:
[Required(ErrorMessage="Please select Disease Type.")]
public string DiseaseType { get; set; }
PatientDBHandle.cs code:
public bool UpdatePatient(Patient patient)
{
connection();
SqlCommand cmd = new SqlCommand("UpdatePatientDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", patient.ID);
cmd.Parameters.AddWithValue("#DiseaseType", patient.DiseaseType);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if(i >= 1)
{
return true;
}
else
{
return false;
}
}
I've created one table Patient
CREATE TABLE [dbo].[Patient] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[DiseaseType] VARCHAR (20) NULL,
PRIMARY KEY CLUSTERED ([ID] ASC)
);
I'm new to mvc, please help.
Instead of using a List<string> and SelectList in your controller, use a List<SelectListItem> instead and load that into your ViewBag:
List<SelectListItem> disease = new List<SelectListItem>();
disease.Add(new SelectListItem { Value = "Select", Text = "Select" });
disease.Add(new SelectListItem { Value = "Cancer", Text = "Cancer" });
disease.Add(new SelectListItem { Value = "Heart", Text = "Heart" });
ViewBag.Diseases = disease;
In your View (Edit.cshtml) use your ViewBag for the dropdown like so:
#Html.DropDownList("DiseaseType", (IEnumerable<SelectListItem>)ViewBag.Diseases, new { htmlAttributes = new { #class = "form-control" } })
Here I have put "DiseaseType" in instead of your model, but only to demonstrate that when you then post your choice, in order to get that value passed back into your controller, take a string called DiseaseType (use your model instead):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TestStack(string DiseaseType)
{
string result = DiseaseType;
return RedirectToAction("Index");
}

Can not retrieve DropdownList value in model using mvc & ado.net

I am sending selectedlist to view using ViewBag. Here is the get method that i pass through ViewBag
public List<Dept> GetDept()
{
connection();
List<Dept> deptList = new List<Dept>();
SqlCommand com = new SqlCommand("Sp_GetDept", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();
//Bind EmpModel generic list using dataRow
foreach (DataRow dr in dt.Rows)
{
deptList.Add(
new Dept
{
DeptId = Convert.ToInt32(dr["DeptId"]),
Name = Convert.ToString(dr["Name"])
}
);
}
return deptList;
}
public ActionResult Create()
{
DeptRepo repo = new DeptRepo();
ViewBag.Dept = new SelectList(repo.GetDept(), "DeptId", "Name");
return View();
}
View Code:
<div class="form-group">
#Html.LabelFor(model => model.Dept, "Department", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Dept", null, "--Select--", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Dept, "", new { #class = "text-danger" })
</div>
</div>
Student model:
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public string Roll { get; set; }
public int DeptId { get; set; }
public virtual Dept Dept { get; set; }
}
post method:
[HttpPost]
public ActionResult Create(Student std)
{
try
{
if (ModelState.IsValid)
{
StudentRepo repo = new StudentRepo();
repo.AddStudent(std);
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
In post method dropdownlist id value found null in student object.
Can anybody tell me how i can retrieve foreignkey Id using mvc and ado.net.
Any kind of help would be greatly appreciated.
Your current code,
#Html.DropDownList("Dept", null, "--Select--",
htmlAttributes: new { #class = "form-control" })
will generate HTML markup for a SELECT element with name attribute value set to Dept
<select class="form-control" id="Dept" name="Dept">
<option value="">--Select--</option>
</select>
Since you are using the Student class as your httppost action method parameter, for model binding to properly map the selected option value to DeptId property of the Student object, you need to make sure that your select element name is also DeptId
If your view is strongly typed to the Student class, you can use DropDownListFor helper method
#Html.DropDownListFor(a => a.DeptId, ViewBag.Dept as IEnumerable<SelectListItem>,
"--Select--", htmlAttributes: new { #class = "form-control" })
Or
You can use DropDownList method and give DeptId as the first param (name of the control) and explicitly specify the collection to use for building the options as the second param.
#Html.DropDownList("DeptId", ViewBag.Dept as IEnumerable<SelectListItem>,
"--Select--", htmlAttributes: new { #class = "form-control" })
This will render the SELECT element with name attribute value set to DeptId and when the form is submitted, model binder will be able to use the selected option value to set it to the DeptId property of the Student object(which is your httppost action method parameter)

Dropdownlist value is null after posting to controller in ASP.NET MVC

I can get all Roles plus actually Role for chosed user, but then When I posting to EditUser action, then Dropdownlist sends null.
I mean When the form posts to my controller, I get null from DropDownList.
Here is my Model
public class EditUserViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<SelectListItem> ApplicationRoles { get; set; }
public string ApplicationRoleId { get; set; }
}
Here is Action
[HttpGet]
public async Task<ActionResult> EditUser(string id)
{
EditUserViewModel model = new EditUserViewModel();
model.ApplicationRoles = RoleManager.Roles.Select(r => new SelectListItem
{
Text = r.Name,
Value = r.Id
}).ToList();
if (!String.IsNullOrEmpty(id))
{
ApplicationUser user = await UserManager.FindByIdAsync(id);
if (user != null)
{
var role = await UserManager.GetRolesAsync(user.Id);
var existingRole = role.First();
string existingRoleId = RoleManager.Roles.Single(r => r.Name == existingRole).Id;
model.Id = user.Id;
model.FirstName = user.FirstName;
model.ApplicationRoleId = existingRoleId;
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name", model.ApplicationRoleId);
}
}
return PartialView("_EditUser", model);
}
And here is DropDownlist from _EditUser.cshtml
<div class="form-group">
#Html.Label("Role typ", htmlAttributes: new { #class = "control-label col-md-6" })
<div class="col-md-12" title="Ange antal datorer som finns i lager">
#Html.DropDownList("RoleId", null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ApplicationRoles, "", new { #class = "text-danger" })
</div>
</div>
Getting null Only from DropDownList, not from #Html.EditorFor
/Thanks in advance!
Forms post back the name/value pairs of their successful form controls. Your generating a <select> element with name="RoleId" but you model does not contain a property named RoleId. Since you want to bind the selected option to the ApplicationRoleId role property, then you view needs to be
#Html.LabelFor(m => m.ApplicationRoleId)
#Html.DropDownListFor(m => m.ApplicationRoleId, Model.ApplicationRoles)
#Html.ValidationMessageFor(m => m.ApplicationRoleId)
Notes:
Your current #Html.Label(..) code does not create a label
associated with your dropdownlist (clicking on it will not set
focus)
The ValidationMessageFor() need to be applied to the property your
binding to, not the SelectList
Delete you ViewBag.RoleId = new SelectList(..) code. Your have
already assigned the selectlist to the ApplicationRoles property
(and you should never need ViewBag if have a view model anyway)
Because you are declare that only HttpGet methods are allow in that method of the controller. Thats why

MVC 5 Multiselect List Values Not Binding to Model On Post

I have a view with several multiselect lists which are declared like this
<div class="col-md-6">
#Html.LabelFor(model => model.Counties, htmlAttributes: new { #class = "control-label" })
#Html.ListBoxFor(model => model.Counties, new MultiSelectList(ViewBag.CountyList, "Value", "Text"), htmlAttributes: new { #class = "form-control", size = 8, tabindex = 26 })
#Html.ValidationMessageFor(model => model.Counties, "", new { #class = "text-danger" })
<span class="small">Ctrl + click to select multiple items</span>
</div>
My view model contains a declaration like this:
public virtual List<long> Counties { get; protected set; }
My action looks like this:
[HttpPost]
public ActionResult Edit(TScholarshipView model, FormCollection form)
{
if (ModelState.IsValid)
{
TScholarship scholarship = Repo.GetScholarship(model.Id);
scholarship = Mapper.Map<TScholarshipView, TScholarship>(model, scholarship);
Repo.SaveOrUpdate(scholarship, HttpContext.User.Identity.Name);
return RedirectToAction("Edit", "AdminScholarship", new { id = model.Id });
}
return View("Scholarship", model);
}
On submit I can look at the post data sent by the browser and it is sending the appropriate data to the server
...&Counties=16&Counties=34&...
When the action begins to execute the value of Counties in the model is null. However I can look at the FormCollection values and the value of form["Counties"] is "16,34". Any ideas why the binding is not occurring?
I noticed this right after I posted the question. The problem was having the setter protected. This prevented the binder from setting the value of the list.
You need to reset the value of ViewBag.CountyList on post event as well.
Or have one property in the model and bind that property to your multi select list box.
Something like
Wrapper / Model
public class CustomerList
{
public List<Customer> Customers { get; set; }
public List<int> SelectedIDs { get; set; }
}
Controller
[HttpGet]
public ActionResult DisplayCustomer()
{
Customer oCustomer = new Customer();
List<Customer> CustomersList = new List<Customer>();
CustomersList.Add(new Customer() { ID = 1, Name = "TestCustomer1", Amt = 123 });
CustomersList.Add(new Customer() { ID = 2, Name = "TestCustomer2", Amt = 234 });
CustomersList.Add(new Customer() { ID = 3, Name = "TestCustomer3", Amt = 324 });
ViewBag.CustList = CustomersList;
return View(new CustomerList() { Customers = CustomersList });
}
[HttpPost]
public void DisplayCustomer(List<int> selectedIds)
{
// do something with the id list
}
View
#model MvcApplication2.Models.CustomerList
#using (Html.BeginForm(#Model.SelectedIDs))
{
#Html.ListBoxFor(m => m.SelectedIDs, new MultiSelectList(#Model.Customers, "ID", "Name", #Model.SelectedIDs))
<input type="submit" value="save" />
}
As mentioned here
Hope that works!!!

dropdownlistfor selected value with viewdata

I am not able to bind the selected value in MVC. Can someone tell me what is wrong with the following code:
#Html.DropDownListFor(x => Model.Members[i].OccupationCd,
(IEnumerable<SelectListItem>)ViewData["ddl_occupation"],
new { #style = "width:100px", #class = "Occupation required" })
public List<SelectListItem> GetOccupation(string selectedValue)
{
List<SelectListItem> selLstOccupation = new List<SelectListItem>();
selLstOccupation.Add(new SelectListItem { Value = "", Text = "---" + ("Select Occupation") + "---" });
selLstOccupation.AddRange(GetData.AllOccupation());
selLstOccupation = GetData.GetSelectedList(selLstOccupation, selectedValue);
return selLstOccupation;
}
public class Member()
{
//code
//code
public int educationCd { get; set; }
}
I found the Solution:
#Html.DropDownListFor(x => Model.Members[i].OccupationCd,new SelectList((IEnumerable<SelectListItem>)ViewData["ddl_occupation"],"Value","Text",Model.Members[i].OccupationCd))
You have to do two things to fix your problem. The first one is to change the GetOccupation method with the following implementation
public List<Occupation> GetOccupation()
{
return GetData.AllOccupation();
}
Then you have to change the dropdown initialization to the following
#Html.DropDownListFor(x => x.Members[i].OccupationCd,
new SelectList(
(IEnumerable<Occupation>)ViewData["ddl_occupation"],
"OccupationCd",
"##HERE YOU ADD THE PROPERTY YOU WANT TO VISUALIZE##",
Model.Members[i].OccupationCd),
"---Select Occupation--",
new { #style = "width:100px", #class = "Occupation required" })
This should fix your problem.

Resources