MVC dropdownlist required field validation not working - c#

I am new to MVC, as part of my work i need to validate drop down list with required field validation, i tried in below way but Validation not working,
When i click on submit button without selecting a dropdown menu Validation is not working.
Model:
[Required(ErrorMessage = "*Required")]
[Display(Name = "Environment")]
public int? Environment { set; get; }
Controller:
List<SelectListItem> environmentlist = new List<SelectListItem>();
environmentlist.Add(new SelectListItem { Text = "SIT", Value = "1" });
environmentlist.Add(new SelectListItem { Text = "UAT", Value = "2" });
environmentlist.Add(new SelectListItem { Text = "PROD", Value = "3" });
ViewBag.EnvironmentList = environmentlist;
View:
#Html.DropDownListFor(model => model.Environment,(IEnumerable<SelectListItem>)ViewBag.EnvironmentList, String.Empty)
#Html.ValidationMessageFor(model => model.Environment)

This can be help in your code,
Public ActionResult yourMethod()
{
if (ModelState.IsValid)
{
// Your code
}
else
{
return View("Same View");
}
}
Learn more about ModelState.IsValid.

Try the following
#Html.DropDownListFor(model => model.Environment,(IEnumerable<SelectListItem>)ViewBag.EnvironmentList, new {required = "required"})

Related

Get selected item in a dropdown list in view to CRUD model

This is done by adding a view from my controller and selecting my dto as template
My DTO
public class Company_DTO
{
public long ID_Company { get; set; }
public string ESTATE_Company { get; set; }
}
MyController
public ActionResult UpdateCompany()
{
ViewBag.ListOfCompanies = DependencyFactory.Resolve<ICompanyBusiness>().GetCompany(); // this return a List<int> and following what I read for viewbag this should be right.
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateCompany([Bind]Company_DTO company_DTO)
{
try
{
//code
}
catch
{
return View();
}
}
View
<div class="form-group">
#Html.DropDownListFor(model => model.ID_Company , ViewBag.ListOfCompanies) // Here I get an error on my #Html that my dto does nothave a list.
</div>
I want the selected item to be ID_Company, but here it seems to be trying to add the whole list when I just want the selected item, I cant find any documentation or question that can solve my issue.
I Cant EDIT the DTO.
Thanks for any help and hope I am being clear enough.
This should solve your problem:
View
<div class="form-group">
#Html.DropDownListFor(model => model.ID_Company, new SelectList(ViewBag.Accounts, "ID_Company", "ESTATE_Company"))
</div>
Supposing your view is strongly typed (#model Company_DTO).
Hope this helps
consider the following example:
public class HomeController : Controller
{
private List<SelectListItem> items = new List<SelectListItem>()
{
new SelectListItem() { Text = "Zero", Value = "0"},
new SelectListItem() { Text = "One", Value = "1"},
new SelectListItem() { Text = "Two", Value = "2"}
};
public ActionResult Index()
{
ViewBag.Items = items;
return View(new Boo() { Id = 1, Name = "Boo name"});
}
}
public class Boo
{
public int Id { get; set; }
public string Name { get; set; }
}
the view:
#model WebApi.Controllers.Boo
#Html.DropDownListFor(x=>x.Id, (IEnumerable<SelectListItem>) ViewBag.Items)
so, ViewBag.ListOfCompanies should contain IEnumerable. Each SelectListItem has Text and Value property , you need to assign ESTATE_Company and ID_Company respectively. something like this:
var companiesList = //get companies list
ViewBag.ListOfCompanies = companiesList.Select(x => new SelectListItem() {Text = x.ESTATE_Company, Value = x.ID_Company.ToString()});
....
#Html.DropDownListFor(x=>x.ID_Company, ViewBag.Items as IEnumerable<SelectListItem>)

Asp.Net Mvc Selectpicker

I am trying to implement a DropDownList Multi Select using Bootstrap Selectpicker for selecting Schools in my application.
I am not very familiar with MVC and JQuery since i have been using webforms for a long time, so i am learning from internet to accomplish.
Here is the scenario:
on my layout, there is a DropDownList:
#*DropDownList Select School*#
#Html.DropDownList("Schools", null, null, new { id = "MultiSelect", #class = "selectpicker form-control", multiple = "", title = "School" })
The code to fill the DropDownList:
public ActionResult Class()
{
IEnumerable<SelectListItem> ListClasses = db.scasy_class
.OrderBy(a => a.class_name)
.Select(c => new SelectListItem
{
Value = c.id.ToString(),
Text = c.class_name,
Selected = false
});
ViewBag.Class = ListClasses.ToList();
ClassViewModel classViewModel = new ClassViewModel()
{
SelectOptions = ListClasses
};
return View(classViewModel);
}
On layout, when the user selects some schools, using the dropdownlist,
$('#MultiSelect').on('change', function () {
$.each($("#MultiSelect option"), function () {
$.post("/Setup/Student/SetSchool/", { school: $(this).val(), selected: $(this).prop('selected') });
});
});
and the controller;
public ActionResult SetSchool(int school, bool selected)
{
ArrayList school_nos = Session["Schools"] as ArrayList;
if (selected)
{
if (!school_nos.Contains(school))
{
school_nos.Add(school);
}
}
else
{
if (school_nos.Contains(school))
{
school_nos.Remove(school);
}
}
Session["Schools"] = school_nos;
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
it is working as it is expected until here.
For the next reload, i am trying to fill the dropdownlist with the same data but show previously selected schools with tick, using Session values, since i will need this information on many other pages.
$(document).ready(function () {
$.getJSON("/Setup/Student/GetSchool/",
function (data) {
var myData = [];
$.each(data, function (index, item) {
if (item.Selected == true) {
myData.push(item.Value);
}
});
//alert(myData);
$('#MultiSelect').selectpicker('val', myData);
});
});
and the controller;
public JsonResult GetSchool()
{
IEnumerable<SelectListItem> ListSchools = db.scasy_school
.OrderBy(a => a.name)
.Select(a => new SelectListItem { Value = a.id.ToString(), Text = a.name});
ArrayList school_nos = Session["Schools"] as ArrayList;
List<SelectListItem> ListSchoolsUpdated = new List<SelectListItem>();
foreach (var item in ListSchools)
{
SelectListItem selListItem;
if (school_nos.Contains(item.Value.ToString()))
{
selListItem = new SelectListItem() { Value = item.Value.ToString(), Text = item.Text, Selected = true };
}
else
{
selListItem = new SelectListItem() { Value = item.Value.ToString(), Text = item.Text, Selected = false };
}
ListSchoolsUpdated.Add(selListItem);
}
return Json(ListSchoolsUpdated, JsonRequestBehavior.AllowGet);
}
Code throws no error, but i cannot have the dropdownlist with selected items shown.
Declare a model class for your page
public class ClassViewModel {
public List<int> SelectedSchools {get; set;}
public List<SelectListItem> Schools {get; set;}
}
Set Selected Schools in your controller action.
Set Your View Model
#model ClassViewModel
Then in your view use this code to show dropdownlist
#Html.ListBoxFor(m=> m.SelectedSchools , Model.Schools, new {id = "MultiSelect", #class = "selectpicker form-control", title = "School" })

Why I am getting "System.Web.Mvc.SelectListItem" in my DropDownList?

I believe I have bound my data correctly, but I can't seem to get my text property for each SelectListItem to show properly.
My model:
public class Licenses
{
public SelectList LicenseNames { get; set; }
public string SelectedLicenseName { get; set; }
}
Controller:
[HttpGet]
public ActionResult License()
{
try
{
DataTable LicsTable = BW.SQLServer.Table("GetLicenses", ConfigurationManager.ConnectionStrings["ProfressionalActivitiesConnection"].ToString());
ProfessionalActivities.Models.Licenses model = new ProfessionalActivities.Models.Licenses();
model.LicenseNames = new SelectList(LicsTable.AsEnumerable().Select(row =>
new SelectListItem
{
Value = row["Description"].ToString(),
Text = "test"
}));
return PartialView("_AddLicense", model);
}
catch (Exception ex)
{
var t = ex;
return PartialView("_AddLicense");
}
}
View:
#Html.DropDownList("LicenseNames", new SelectList(Model.LicenseNames, "Value", "Text", Model.LicenseNames.SelectedValue), new { htmlAttributes = new { #class = "form-control focusMe" } })
Use the Items property of your LicenseNames property which is of type SelectList
#Html.DropDownList("SelectedLicenseName", new SelectList(Model.LicenseNames.Items,
"Value", "Text", Model.LicenseNames.SelectedValue))
Or with the DropDownListFor helper method
#Html.DropDownListFor(d=>d.SelectedLicenseName,
Model.LicenseNames.Items as List<SelectListItem>)
So when you post your form, you can inspect the SelectedLicenseName property
[HttpPost]
public ActionResult Create(Licenses model)
{
//check model.SelectedLicenseName
}
I explicitly set the dataValueField and dataTextField names.
new SelectListItem
{
Value = row["Description"].ToString(),
Text = "test"
}), "Value", "Text");
Then there's no need to write Model.LicenseNames.Items as List<SelectListItem> in your views (as suggested in your accepted answer).

Defining a select list through controller and view model

I have a View Model that looks like this:
public class SomeViewModel
{
public SomeViewModel(IEnumerable<SelectListItem> orderTemplatesListItems)
{
OrderTemplateListItems = orderTemplatesListItems;
}
public IEnumerable<SelectListItem> OrderTemplateListItems { get; set; }
}
I then have an Action in my Controller that does this:
public ActionResult Index()
{
var items = _repository.GetTemplates();
var selectList = items.Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }).ToList();
var viewModel = new SomeViewModel
{
OrderTemplateListItems = selectList
};
return View(viewModel);
}
Lastly my view:
#Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text"), "Please select an order template")
The code works fine and my select list populates wonderfully. Next thing I need to do is set the selected value that will come from a Session["orderTemplateId"] which is set when the user selects a particular option from the list.
Now after looking online the fourth parameter should allow me to set a selected value, so if I do this:
#Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text", 56), "Please select an order template")
56 is the Id of the item that I want selected, but to no avail. I then thought why not do it in the Controller?
As a final attempt I tried building up my select list items in my Controller and then passing the items into the View:
public ActionResult Index()
{
var items = _repository.GetTemplates();
var orderTemplatesList = new List<SelectListItem>();
foreach (var item in items)
{
if (Session["orderTemplateId"] != null)
{
if (item.Id.ToString() == Session["orderTemplateId"].ToString())
{
orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString(), Selected = true });
}
else
{
orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString() });
}
}
else
{
orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString() });
}
}
var viewModel = new SomeViewModel
{
OrderTemplateListItems = orderTemplatesList
};
return View(viewModel);
}
Leaving my View like so:
#Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text"), "Please select an order template")
Nothing!
Why isn't this working for me?
You say "56 is the Id of the item that I want selected, but to no avail"
Should the fourth parameter you refer to be a string, not an integer, like so:
#Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text", "56"), "Please select an order template")

Getting Multiple Selected Values in Html.DropDownlistFor

#Html.DropDownListFor(m => m.branch, CommonMethod.getBranch("",Model.branch), "--Select--", new { #multiple = "multiple" })
#Html.DropDownListFor(m => m.division, CommonMethod.getDivision(Model.branch,Model.division), "--Select--", new { #multiple = "multiple" })
I have two instances of DropDownListFor. I want to set selected as true for those which have previously stored values for Model.branch and Model.division. These are string arrays of stored ids
class CommonMethod
{
public static List<SelectListItem> getDivision(string [] branchid , string [] selected)
{
DBEntities db = new DBEntities();
List<SelectListItem> division = new List<SelectListItem>();
foreach (var b in branchid)
{
var bid = Convert.ToByte(b);
var div = (from d in db.Divisions where d.BranchID == bid select d).ToList();
foreach (var d in div)
{
division.Add(new SelectListItem { Selected = selected.Contains(d.DivisionID.ToString()), Text = d.Description, Value = d.DivisionID.ToString() });
}
}
}
return division;
}
}
The returned value of division is selected as true for the selected item in the model, but on view side it is not selected.
Use a ListBoxFor instead of DropDownListFor:
#Html.ListBoxFor(m => m.branch, CommonMethod.getBranch("", Model.branch), "--Select--")
#Html.ListBoxFor(m => m.division, CommonMethod.getDivision(Model.branch, Model.division), "--Select--")
The branch and division properties must obviously be collections that will contain the selected values.
And a full example of the proper way to build a multiple select dropdown using a view model:
public class MyViewModel
{
public int[] SelectedValues { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
}
that would be populated in the controller:
public ActionResult Index()
{
var model = new MyViewModel();
// preselect items with values 2 and 4
model.SelectedValues = new[] { 2, 4 };
// the list of available values
model.Values = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
new SelectListItem { Value = "4", Text = "item 4" },
};
return View(model);
}
and in the view:
#model MyViewModel
...
#Html.ListBoxFor(x => x.SelectedValues, Model.Values)
It is the HTML helper that will automatically preselect the items whose values match those of the SelectedValues property.
For me it works also for #Html.DropDownListFor:
Model:
public class MyViewModel
{
public int[] SelectedValues { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
}
Controller:
public ActionResult Index()
{
var model = new MyViewModel();
// the list of available values
model.Values = new[]
{
new SelectListItem { Value = "2", Text = "2", Selected = true },
new SelectListItem { Value = "3", Text = "3", Selected = true },
new SelectListItem { Value = "6", Text = "6", Selected = true }
};
return View(model);
}
Razor:
#Html.DropDownListFor(m => m.SelectedValues, Model.Values, new { multiple = "true" })
Submitted SelectedValues in controller looks like:
Though quite old thread but posting this answer after following other answers here, which unfortunately didn't work for me. So, for those who might have stumbled here recently or in near future, Below is what has worked for me.
This is what helped me
The catch for me was MultiSelectList class and I was using SelectList.
Don't know situation in 2012 or 2015. but, now both these helper methods #Html.DropDownListFor and #Html.ListBoxFor helper methods accept IEnumerable<SelectListItem> so you can not pass any random IEnumerable object and expect these helper methods to do the job.
These helper methods now also accept the object of SelectList and MultiSelectList classes in which you can pass the selected values directly while creating there objects.
For example see below code how i created my multi select drop down list.
#Html.DropDownListFor(model => #Model.arrSelectUsers, new MultiSelectList(Model.ListofUsersDTO, "Value", "Text", #Model.arrSelectUsers),
new
{
id = "_ddlUserList",
#class = "form-control multiselect-dropdown",
multiple = "true",
data_placeholder = "Select Users"
})

Categories

Resources