DropDownList not selected in Edit page - c#

I Created Controller with "MVC 5 Controller with views, using Entity Framework" and modify "DropDownList" code in "Edit" view to
#Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.prdepno, new { #class = "form-control" })
in Controller use ViewBag
personal personal = db.personals.Find(id);
ViewBag.prdepno = new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);
no error ,but dropdownlist not selected
I lookup from Adding a css class to select using #Html.DropDownList()
and other question try to do that, but It not work (for me)
I don't know to do
(sorry, in my communication.)

I think you need to change the name of ViewBag Object
personal personal = db.personals.Find(id);
ViewBag.DwPrdeps= new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);
after that use ViewBag.DwPrdeps in your view
#Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.DwPrdeps, new { #class = "form-control" })

Try With this code It's Work properly
Code Generate/ Model
public class CityList
{
public string city { get; set; }
}
public static IEnumerable<SelectListItem> GetCity()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "Dhaka", Value = "dhk" },
new SelectListItem{Text = "Chittagong", Value = "CTG" }
};
return items;
}
For Create
ViewBag.city = new SelectList(GetCity(), "Text", "Value");
#Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { #class = "form-control select2", required = "required" })
For edit
ViewBag.city = new SelectList(GetCity(), "Text", "Value",model.city);
#Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { #class = "form-control select2", required = "required" })
You Can Try This it's work fine.

Related

How to set default value "0" to text "Select" in DropDownList in MVC?

Below is the dropdownlist of Country. I want selected text "Select" which is working.
#Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
new { #class = "form-control" })
Now I want to set the value "0" for text "Select" which is by default selected. Currently the value for "Select" is blank as shown below.
How can I do this? The value "Select" is not in the data source. I have to access this selected value in JQuery.
I have tried with these two but none of those are working.
#Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { #class = "form-control", #selected = "0" })
And
#Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { #class = "form-control", #selected = "0" })
Below is the controller code for CountryName values
ViewBag.CountryName = dbLMS.CountryMasters.Select(c => new { c.CountryId, c.CountryName }).OrderBy(c => c.CountryName).ToList();
You can do as follows:
Option-1:
#{
var countrySelectList = new SelectList(ViewBag.CountryName, "CountryId", "CountryName");
List<SelectListItem> countrySelectListItems = countrySelectList.ToList();
countrySelectListItems.Insert(0, (new SelectListItem { Text = "Please select", Value = "0", Selected = true }));
}
#Html.DropDownList("ddlCountryName", countrySelectListItems , new { #class = "form-control" })
Option-2:
In the controller method:
List<SelectListItem> selectListItems = dbLMS.CountryMasters.Select(a => new SelectListItem()
{
Text = a.CountryName,
Value = a.CountryId
}).ToList();
selectListItems.Insert(0, new SelectListItem(){Text = "Selet Country", Value = "0", Selected = true});
ViewBag.CountrySelectList = selectListItems;
Then in the view:
#Html.DropDownList("ddlCountryName", (List<SelectListItem>)ViewBag.CountrySelectList, new { #class = "form-control" })
new SelectList(ViewBag.CountryName, "CountryId", "CountryName", //Default value)
You dont really need a value for Select. For the model, keep the Required validation attribute.
This will ensure the value is selected. This way you dont have to check in the backend.

How to keep the id from the selectlist when using multiple columns in the textfield

I am trying to show multiple columns from my database in a dropdownlist using a SelectList
public ActionResult Create()
{
var times = db.Show_Courses
.Select(x =>
new {
id = x.show_course_id,
times = x.show_course_before + "," + x.show_course_after
});
ViewBag.course_id = new SelectList(times, "id", "times");
return View();
}
It shows up properly in the view but in the database the value of the id is 0
This was my code before i wanted to show two columns in the textfield of the selectlist
public ActionResult Create()
{
ViewBag.course_id = new SelectList(db.Show_Courses, "show_course_id", "show_course_time_before");
return View();
}
And here is my code in the view
<div class="form-group">
#Html.LabelFor(model => model.course_show_id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("course show id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.course_show_id, "", new { #class = "text-danger" })
</div>
</div>
So my question is how can I display 2 values in the Textfield of the Selectlist without the id becoming 0?
You could generate SelectList manually.
For example,
ViewBag.course_id = db.Show_Courses
.Select(x => new SelectListItem {
Text = x.show_course_before + "," + x.show_course_after,
Value = x.show_course_id.ToString() })
.ToList();
I personally like to use strongly type model. You can read more here
Your code seems to be fine, you need to map the dropdown to according value from model: show_course_id - from what I see, so please update your dropdown to:
#Html.DropDownList("show_course_id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { #class = "form-control" } })

session bind with #Html.DropDownListFor

I have one of a method as following in my controller
Code
var companies = ...
List<CompanyModel> listOfCompanies = new List<CompanyModel>();
foreach (var item in companies)
{
listOfCompanies.Add(new CompanyModel(item.CompanyId, item.CompanyName));
}
ViewBag.Company = listOfCompanies;
View page
#Html.DropDownListFor(m => m.Company, new SelectList(ViewBag.Company, "id", "name"), "Select company", new { #class = "form-control" })
this is working fine , I'm trying trying to use session instead of viewbag here.
So for that I did
var companies = ...
List<CompanyModel> listOfCompanies = new List<CompanyModel>();
foreach (var item in companies)
{
listOfCompanies.Add(new CompanyModel(item.CompanyId, item.CompanyName));
}
Session["CompanyData"] = listOfCompanies;
View page
#Html.DropDownListFor(m => m.Company, new SelectList(Model.Company, "id", "name", Session["CompanyData"]), "Select company", new { #class = "form-control" })
but this is not working properly, whats the path to achieve this
Have you tried simply replacing ViewBag with Session?
#Html.DropDownListFor(m => m.Company, new SelectList((List<CompanyModel>)Session["CompanyData"], "id", "name"), "Select company", new { #class = "form-control" })

Getting drop down city list to show after state is selected ASP MVC5

I feel like I have a working idea but I am getting a "Object reference not set to an instance of an object" error when I build the application. I am simply trying to display a drop down list for cities after the selection for state is made. I have a list of states in a seperate class that I am using for a drop down list in a form. What I am attempting to do is grab the selected state and pass it as a perameter into a different class in order to select the correct list of cities to be displayed as another drop down. So if someone selects washington state then cities such as Seattle and Tacoma show up and not cities from a different state. Here is the razor for the drop downs (the state works fine):
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.State, WebGridProject.Models.StateCodes.GetStatesList(), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, WebGridProject.Models.CityNames.GetStateCities(Model.State), new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
And here is the class for cities:
public class CityNames
{
public static IEnumerable<SelectListItem> GetStateCities(string stateName)
{
IList<SelectListItem> cities = new List<SelectListItem>();
switch (stateName)
{
case "AK":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Anchorage", Value = "Anchorage"},
new SelectListItem() {Text = "Fairbanks", Value = "Fairbanks"},
};
break;
case "AL":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Auburn", Value = "Auburn"},
new SelectListItem() {Text = "Birmingham", Value = "Birmingham"},
new SelectListItem() {Text = "Dothan", Value = "Dothan"},
new SelectListItem() {Text = "Mobile", Value = "Mobile"},
};
break;
case "AZ":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Pheonix", Value = "Pheonix"},
new SelectListItem() {Text = "Flagstaff", Value = "Flagstaff"},
new SelectListItem() {Text = "Prescott", Value = "Prescott"},
new SelectListItem() {Text = "Tucson", Value = "Tucson"},
};
break;
case "AR":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Fayetteville", Value = "Fayetteville"},
new SelectListItem() {Text = "Fort smith", Value = "Fort smith"},
new SelectListItem() {Text = "Jonesboro", Value = "Jonesboro"},
new SelectListItem() {Text = "Texarkana", Value = "Texarkana"},
};
break;
default:
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Please Select State", Value = "Please Select State"},
};
break;
}
return cities;
}
}
to me the error seemed to be pointing to there being no default value and having an issue with loading a null value. But I have a default case in the switch statement to cover this issue. I am pretty new to MVC and I will continue to work on this on my own. But if anyone has any ideas I am all ears because I am struggling to figure this out. Just FYI, the states class is also an IList<> that returns the list of state names.
request for action to be posted:
public ActionResult MyHomePage()
{
return View();
}
//Post method
[HttpPost]
public ActionResult MyHomePage(WebGridTable TWG)
{
try
{
if (ModelState.IsValid)
{
UserManager UM = new UserManager();
UM.addNewUser(TWG);
ModelState.Clear();
return View();
}
return View();
}
catch (Exception e)
{
return View("Error");
}
}
action doesnt really mean anything without the method I wrote for managing the form:
public void addNewUser(WebGridTable AddNew)
{
using (WebGridDBEntities4 db = new WebGridDBEntities4())
{
WebGridTable TWG = new WebGridTable();
TWG.Name = AddNew.Name;
TWG.DOB = AddNew.DOB;
TWG.AddressLine1 = AddNew.AddressLine1;
// TO DO: Figure out issue with accepting null value into database.
if (AddNew.AddressLine2 != null)
{
TWG.AddressLine2 = AddNew.AddressLine2;
}
else if (AddNew.AddressLine2 == null)
{
TWG.AddressLine2 = 0;
}
TWG.State = AddNew.State;
TWG.City = TWG.City;
TWG.Zip = AddNew.Zip;
TWG.Gender = AddNew.Gender;
db.WebGridTables.Add(TWG);
db.SaveChanges();
}
}
You need to use JQuery actions on Changes of the States DropDownList. Send the value to a specific Action in your Controller and Call your States.GetStatesName('Value') in that. Check the Code below. I think it would help.
$("#State").on('change',function () {
var loadingoption = $('<option></option>').text("Pleas Wait");
$('#city').attr("disabled","disabled").empty().append(loadingoption);
jQuery.getJSON("/Home/CityJson/" + $("#State > option:selected").attr("value"), function (data) {
var defaultoption = $('<option value="">Please choose a City</option>');
$('#city').removeAttr("disabled").empty().append(defaultoption);
jQuery.each(data, function (i) {
var option2 = $('<option></option>').attr("value", data[i].Name).text(data[i].Name);
$("#city").append(option2);
});
});
});
I used ActionResult "CityJson" in my HomeController. So choose your Action in getJSON.
Here is the Controller:
public ActionResult CityJson(string id)
{
var state = db.States.FirstOrDefault(x => x.Name == id);
var model = db.Cities.Where(x => x.StateId == state.Id).Select(x => new { x.Name }).ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
you can call your actions inside the Class and send them using Json.
Good Luck.

Remove blank/empty entry at top of EnumDropDownListFor box

I am rendering a drop down list box using my enums and I only have 3 options, but for some reason it is displaying four. The top and default option is simply blank/empty and I want this removed. I want the top/default value to be 'Option1'.
Enums:
public enum EventType
{
[Display(Name = "Option 1")]
Option1,
[Display(Name = "Option 2")]
Option2,
[Display(Name = "Option 3")]
Option3
}
View:
#Html.EnumDropDownListFor(model => model.EventType, null, new { #id = "eventType", #class = "form-control" })
Thanks for your help.
Your second parameter is the "Option Label" which is used to set the first item in the dropdown. From the documentation: "The text for a default empty item"
Use an overload that doesn't take in the option label:
#Html.EnumDropDownListFor(model => model.EventType, new { #id = "eventType", #class = "form-control" })
UPDATE
I just tried your code. When I do both:
#Html.EnumDropDownListFor(model => model.EventType, null, new { #id = "eventType", #class = "form-control" })
And
#Html.EnumDropDownListFor(model => model.EventType, new { #id = "eventType", #class = "form-control" })
I get:
The only time I get another option in the dropdown is when I pass in a string as the second parameter, such as "Select..."
Any chance you are doing something with javascript to add an item to the dropdown?
I also had the same problem.Solved this starting enum from 0 not 1 .
public enum EventType
{
[Display(Name = "Option 1")]
Option1,
[Display(Name = "Option 2")]
Option2,
[Display(Name = "Option 3")]
Option3
}
#Html.EnumDropDownListFor(model => model.EventType,
new {#id = "eventType", #class = "form-control" })
I spent some time getting the above to work and was unsuccessful.
I found an alternative way :
HTML:
#Html.DropDownList("types",
Helper.Gettypes(),
new { #class = "form-control", #title = "--- Choose ---" })
Code:
public static List<SelectListItem> Gettypes()
{
var enums = Enum.GetNames(typeof(WorkLogType)).ToList();
var selectLIst = enums.Select(x => new SelectListItem {Value = x, Text = x}).ToList();
return selectLIst;
}

Categories