problems with html helper method - asp.net-mvc

I can't figure out how to send a parameter from a dropdownlist to my model. Could someone please show me an example of how to do this?

As always you start by defining a model:
public class MyViewModel
{
public string SelectedValue { get; set; }
public SelectList Items
{
get
{
return new SelectList(new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
}, "Value", "Text");
}
}
}
Controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// You will get the selected value inside model.SelectedValue here
// => do something with it
....
}
}
Strongly typed view:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.SelectedValue, Model.Items) %>
<input type="submit" value="OK" />
<% } %>

public ActionResult Edit(int id)
{
Affiliate affiliate = affiliateRepository.GetAffiliate(id);
List<SelectListItem> StateList = new List<SelectListItem>();
SelectListItem item;
Dictionary<string, string> dictState = S127Global.Misc.getStates();
foreach (KeyValuePair<string, string> k in dictState)
{
item = new SelectListItem();
item.Text = k.Value;
item.Value = k.Key;
StateList.Add(item);
}
item = new SelectListItem();
item.Text = " - Select State - ";
item.Value = "";
StateList.Insert(0, item);
//create new select list with affiliate.state as the selected value in ViewData
ViewData["State"] = new SelectList(StateList.AsEnumerable(), "Value", "Text",affiliate.State);
return View(affiliate);
}
code for view
<div class="editor-label">
<%: Html.LabelFor(model => model.State) %>
</div>
<div class="editor-field">
<%: Html.DropDownList("State")%>
<%: Html.ValidationMessageFor(model => model.State) %>
</div>

Related

Dropdown Mvc Display Default Selected Item

I am new in MVC, I would like to ask if you can teach me how to set/display the default item in the dropdown list?
in the Controller..
[HttpGet]
public ActionResult Edit(int ID)
{
EmployeeDBEntities o = new EmployeeDBEntities();
Employee e = new Employee();
e = o.Employees.Single(x => x.EMP_ID == ID);
ViewBag.Dept = o.uspDeptCbo().Select(x => new SelectListItem { Value = x.DEPT_ID.ToString() , Text=x.DEPARTMENT });
return View(e);
}
View
<div class="editor-field">
#Html.DropDownList("Dept",string.Empty)
#Html.ValidationMessageFor(model => model.DEPT_ID)
</div>
i got it!
in the controller..
enter code here
[HttpGet]
public ActionResult Edit(int ID)
{
ViewBag.Dept = o.uspDeptCbo().Select(x => new SelectListItem { Text = x.DEPARTMENT, Value = x.DEPT_ID.ToString(), Selected = (x.DEPT_ID.ToString() == "3") });
}
in the view..
<fieldset>
#Html.DropDownList("Dept", string.Empty)
</fieldset>
Thank you.

Dropdown list with population with where clause

I want to populate the second dropdown list GetCity() with values from a Data Base that are dependent on whatever was selected in the the first list or GetCounty() dropdown. Where would i add the where clause?
public class NewsModel : BaseModel
{
[Required]
public int? FKCountyId { get; set; }
public string County { get; set; }
[Required]
public int? FKCityId { get; set; }
public string City { get; set; }
public List<SelectListItem> GetCounty()
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Please select County", Value = "" });
foreach (var item in LambertonContext.NewsCounties)
{
lst.Add(new SelectListItem() { Text = item.County, Value = item.PKCountyId.ToString() });
}
return lst;
}
public List<SelectListItem> GetCity()
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Please select City", Value = "" });
foreach (var item in LambertonContext.NewsCities)
{
lst.Add(new SelectListItem() { Text = item.City, Value = item.PKCityId.ToString() });
}
return lst;
}
}
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(m => m.FKCountyId, new { #class = "col-sm-2 col-sm-2 control-label" })
<div class="col-sm-10">
#Html.DropDownListFor(m => m.FKCountyId, Model.GetCounty())
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.FKCityId, new { #class = "col-sm-2 col-sm-2 control-label" })
<div class="col-sm-10">
#Html.DropDownListFor(m => m.FKCityId, Model.GetCity())
</div>
</div>
You will need to pass the CountyId to your GetCity() and filter your list;
try this:
public List<SelectListItem> GetCity(string CountyId)
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Please select City", Value = "" });
foreach (var item in LambertonContext.NewsCities.Where(FKCountyId == GetCounty().Value))
{
lst.Add(new SelectListItem() { Text = item.City, Value = item.PKCityId.ToString() });
}
return lst;
}

Pass SelectedValue of DropDownList in Html.BeginForm() in ASP.NEt MVC 3

This is my View Code:
#using(Html.BeginForm(new { SelectedId = /*SelectedValue of DropDown*/ })) {
<fieldset>
<dl>
<dt>
#Html.Label(Model.Category)
</dt>
<dd>
#Html.DropDownListFor(model => Model.Category, CategoryList)
</dd>
</dl>
</fieldset>
<input type="submit" value="Search" />
}
As code shown I need to pass the dropdown selected value to the action in BeginForm() Html helper. What is your suggestion?
The selected value will be passed when the form is submitted because the dropdown list is represented by a <select> element. You just need to adapt your view model so that it has a property called SelectedId for example to which you will bind the dropdown:
#using(Html.BeginForm() )
{
<fieldset>
<dl>
<dt>
#Html.LabelFor(x => x.SelectedId)
</dt>
<dd>
#Html.DropDownListFor(x => x.SelectedId, Model.CategoryList)
</dd>
</dl>
</fieldset>
<input type="submit" value="Search" />
}
This assumes the following view model:
public class MyViewModel
{
[DisplayName("Select a category")]
public int SelectedId { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
}
that will be handled by your controller:
public ActionResult Index()
{
var model = new MyViewModel();
// TODO: this list probably comes from a repository or something
model.CategoryList = new[]
{
new SelectListItem { Value = "1", Text = "category 1" },
new SelectListItem { Value = "2", Text = "category 2" },
new SelectListItem { Value = "3", Text = "category 3" },
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// here you will get the selected category id in model.SelectedId
return Content("Thanks for selecting category id: " + model.SelectedId);
}

how can get data in drop down list from data base in mvc3.?

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>

MVC - Problem with DataBinding to a Collection using a Custom Template

I am trying to bind to a Model that has a collection property, specifically a List. For the purposes of this example, this represents a list of user roles:
public class RolesModel
{
private List<SelectListItem> _Roles = null;
public string Name { get; set; }
public List<SelectListItem> Roles
{
get {
if (_Roles == null) { _Roles = new List<SelectListItem>(); }
return _Roles;
}
set { _Roles = value; }
}
}
I am binding this to a strongly-typed view via the following Controller:
public class TestController : Controller
{
RolesModel myModel = new RolesModel();
[HttpGet]
public ActionResult Edit()
{
myModel.Name = "Joe Bloggs";
myModel.Roles = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Member", Selected = true },
new SelectListItem { Value = "2", Text = "Manager", Selected = true },
new SelectListItem { Value = "3", Text = "Administrator", Selected = false }
};
return View(myModel);
}
[HttpPost]
public ActionResult Edit(RolesModel m)
{
// !!! m.Roles is always empty !!!
return View("Results", m);
}
}
This then invokes the following view:
#model MyProject.WebUI.Models.RolesModel
#using (Html.BeginForm())
{
<p>
#Html.LabelFor(m => m.Name)
#Html.EditorFor(m => m.Name)
</p>
<div>
#Html.EditorFor(m => m.Roles, "CheckBoxList")
</div>
<p>
<input type="submit" value="Save" />
</p>
}
Note the template specific call to my custom editor template in '/Views/Shared/EditorTemplates/CheckBoxList.cshtml' this looks like this:
#model List<System.Web.Mvc.SelectListItem>
<h3>Type: #Html.LabelFor(m => m)</h3>
<ul>
#for (int i = 0; i < Model.Count; i++)
{
<li>
#Html.CheckBoxFor(m => m[i].Selected)
#Html.LabelFor(m => m[i].Selected, Model[i].Text)
#Html.HiddenFor(m => m[i].Value)
</li>
}
</ul>
The idea being that each SelectListItem is represented by the Html rendered by the loop.
The first part of the process appears to work correctly, The form is presented as expected and you can update the 'Name' text box and the check/uncheck the checkboxes.
The problem is that when the form is posted back to the controller, the Roles collection is never populated.
I'm new to MVC and thought that the framework actually re-constructed the model data from the post via the enforced form element naming convention. I'm obviously missing an important point and I'm hoping someone can point me in the right direction.
Thanks, and apologies for the long post.
Here's how you could proceed:
#model MyProject.WebUI.Models.RolesModel
#using (Html.BeginForm())
{
<p>
#Html.LabelFor(m => m.Name)
#Html.EditorFor(m => m.Name)
</p>
<div>
<ul>
#Html.EditorFor(m => m.Roles)
</ul>
</div>
<p>
<input type="submit" value="Save" />
</p>
}
and inside the EditorTemplate (/Views/Shared/EditorTemplates/SelectListItem.cshtml):
#model System.Web.Mvc.SelectListItem
<h3>Type: #Html.LabelFor(m => m)</h3>
<li>
#Html.CheckBoxFor(m => m.Selected)
#Html.LabelFor(m => m.Selected, Model.Text)
#Html.HiddenFor(m => m.Value)
</li>
Notice the simplification of the editor template. It no longer takes a List<SelectListItem> as model but simply a SelectListItem. It will automatically be invoked for each element of the Roles collection so that you don't need to write any loops. Just follow the conventions.
I would also simplify your view model like this:
public class RolesModel
{
public string Name { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
}
and your controller:
public class TestController : Controller
{
public ActionResult Edit()
{
var myModel = new RolesModel
{
Name = "Joe Bloggs",
Roles = new[]
{
new SelectListItem { Value = "1", Text = "Member", Selected = true },
new SelectListItem { Value = "2", Text = "Manager", Selected = true },
new SelectListItem { Value = "3", Text = "Administrator", Selected = false }
}
};
return View(myModel);
}
[HttpPost]
public ActionResult Edit(RolesModel m)
{
// m.Roles should be correctly bound
return View("Results", m);
}
}

Resources