I'm working with ASP.NET MVC 5 and Entity Framework 6, and I'm having a problem with the model selected value (only for decimal values) in my views.
That only happen when i'm getting data from database, if i try to submit the form, the value get back and is correctly selected.
This is my ViewModel
public class Regulacion
{
public IEnumerable<SelectListItem> ListaPorcentajePuntos
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text="0,625%" , Value = "0,625"},
new SelectListItem { Text="1%" , Value = "1"},
new SelectListItem { Text="1,25%", Value="1,25" },
new SelectListItem { Text="2,5%" , Value = "2,5"},
new SelectListItem { Text="5%" , Value = "5"},
};
}
}
public decimal? PorcentajePunto { get; set; }
//other stuff
public Regulacion(Reg reg)
{
PorcentajePunto = reg.PorcentajePunto;
}
}
And i'm using it in the view like this
#Html.DropDownListFor(x => x.PorcentajePunto, Model.ListaPorcentajePuntos, "Please select", new { #class = "form-control"})
I'm pretty sure, the problem become when i fetch the data from EF and decimal precision, because, when I'm debugging, the PorcentajePunto property stored 5.00 instead of 5, if i manually modify the property to 5 it works perfectly.
I read this question and try to use SelectList instead of SelectListItem but wasn't the solution
How can i deal with it?
Thanks!
EDIT
I'm fetching the Regulacion data like this
using(var db = new DBTrafosContext())
{
var a = db.Reg.FirstOrDefault();
if(a != null){
Regulacion newRegulacion = new Regulacion(a);
}
}
Related
In my ViewModel i got two fields :
public AdTypeEnum Type { get; set; }
public IList<SelectListItem> TypeEnumList { get; set; }
That's how i fill the list :
public void SetLists()
{
TypeEnumList = new List<SelectListItem>();
TypeEnumList.Add(new SelectListItem { Value = "0", Text = "Select the type"});
foreach (var en in Enum.GetValues(typeof(AdTypeEnum)).Cast<AdTypeEnum>())
{
TypeEnumList.Add(new SelectListItem
{
Value = ((int)en).ToString(),
Text = en.ToString(),
Selected = Type == (AdTypeEnum)en ? true : false
});
}
}
And then I'm just rendering a dropdown on my View :
#Html.DropDownListFor(x => x.Type, Model.TypeEnumList, new { #class = "form-control" })
But the selected value doesn't render and the first option is always selected. When I check the select in HTML I found that no one of the options got selected attribute, but when I debug my controller method I can see that always one of the selectListItem have the propety Selected=true. Why does it suddenly disappear when my view is rendering?
Ok I already found out the result. I just had to change the Type from Enum into int and correctly populate it. Everything works! :)
Hi I have Dropdown in Index page where user needs to select lists. Values are coming from Database. I took this dropdown value into session so I can carry this to Httppost.
Below is my code in Index page :
var activitydropdown = orderdata.uspApp_ActivityPageReportname(Convert.ToInt32(newid)).ToList();
List<SelectListItem> activitypage = new List<SelectListItem>();
if (activitydropdown != null && activitydropdown.Count > 0)
{
foreach (var activityresults in activitydropdown)
{
activitypage.Add(new SelectListItem
{
Text = activityresults.name,
Value = activityresults.id.ToString(),
});
}
}
ViewData["activitydropdown"] = activitypage;
Session["activitydropdown"] = activitypage;
And this is my code in view :
#using (Html.BeginForm("Index", "Automation", new { step = "2" }, FormMethod.Post, new { id = "frmIndex" }))
{
#Html.DropDownList("DrpaActivity", ViewData["activitydropdown"] as List<SelectListItem>, "All", new { style = "margin-left:694px;margin-bottom:20px;", onchange = "submit();" })
Now when user selects list from dropdown, i need to carry that text to my httpost index. Now in httpost index, in debug mode if i see this code :
var sessionlistautomation = Session["activitydropdown"];
I can see text and value and selected is false for every item. So how can i carry text here selected from Index to httpost, so when user selects list from dropdown, it stores that text value.
It will be available in your Request i.e.
Request["DrpaActivity"]
However I would strongly advise using ViewModels instead as they're typesafe, less room for error and easier to use.
If you create a view model, like below:
public class AViewModel
{
public string DrpaActivity { get; set; }
public List<SelectListItem> ActivitySelectList { get; set; }
}
In your Index you can return it like this:
public ActionResult Index()
{
var model = new AViewModel();
// set the select list i.e.
model.ActivitySelectList = // get from db etc
return View(model);
}
Then in your view declare the model at the top
#model AViewModel
...
Set your dropdown like this:
#Html.DropDownListFor(m => m.DrpaActivity, Model.ActivitySelectList as List<SelectListItem>, "All", new { style = "margin-left:694px;margin-bottom:20px;", onchange = "submit();" })
You can then get your selected drop-down in your post as follows:
[HttpPost]
public ActionResult Index(AViewModel model)
{
var isValid = model.DrpaActivity;
return View(model);
}
I have the following on my controller:
string preferredLanguage = "fr-ca";
ViewData["Languages"] = new SelectList(languages, "Code", "Name", preferredLanguage);
On the view:
#Html.DropDownList("Languages", (SelectList)ViewData["Languages"], new { id = "Languages" });
My problem here is my dropdown is not setting the selected index of dropdown to the preferred language which is supposed to be French.
Note:
The values inside the languages:
1) Name = "English"
Code = "en-us"
2) Name = "French"
Code = "fr-ca"
And the dropdown shows two languages, English and French. English is set as selected index but what I want is French.
The reason I show the languages this way because this object are being retrieved from the database my a method and not by hardcoded. Thanks in advance!
I'd recommend using strongly-typed helpers bound to a model; something along these lines:
Model:
public class LanguageFormModel
{
public string SelectedLanguage { get; set; }
public SelectList Languages { get; set; }
}
Action:
[HttpGet]
public ActionResult YourActionName()
{
// replace this with however you're getting your language variable
var languages = new CollectionOfSomeSort();
var model = new LanguageFormModel()
{
SelectedLanguage = "fr-ca",
Languages = new SelectList(languages, "Code", "Name", "fr-ca")
};
return View(model);
}
View:
#model Your.Fully.Qualified.Namespace.LanguageFormModel
#Html.LabelFor(m => m.SelectedLanguage)
#Html.DropDownListFor(m => m.SelectedLanguage, Model.Languages, "Select one...")
I'm personally not a huge fan of using ViewData for anything other than simple messages, and even then I use TempData, since I'm mostly just showing confirmations/alerts.
This is working fine for me.
Dictionary<string, string> languages = new Dictionary<string, string>() { { "en-us", "English" }, { "fr-ca", "French" } };
ViewData["Languages"] = new SelectList(languages, "key", "value", "fr-ca");
IN VIEW
#Html.DropDownList("Language", ViewData["Languages"] as SelectList, new { id = "Languages" })
this is ok:
#Html.DropDownList("languages")
I want to select the default value in drop down list where policyId = 7 but it didn't select that value, what i am doing wrong?
Controller:
var pm = new ManagerClass();
IEnumerable<myClass> po = pm.GetDataFromDb();
IEnumerable<SelectListItem> Policies = new SelectList(po, "PolicyID", "PolicyName", new { PolicyID = 7 });
ViewBag.Policies = Policies;
View:
#Html.DropDownListFor(m => m.PolicyID, ViewBag.Policies as IEnumerable<SelectListItem>, new { #class = "dropdown-field"})
It's because it's not actually selecting the value in the SelectList.
First, to make it nicer, put the items in your view model to prevent the cast (this is better practice too):
public class MyModel
{
public int PolicyID { get; set; }
public List<SelectListItem> Policies { get; set; }
//rest of your model
}
Then populate it:
var model = new MyModel();
model.Policies = po
.Select(p => new SelectListItem
{
Text = p.PolicyName,
Value = p.PolicyID.ToString(),
Selected = p.PolicyID == currentPolicyId //change that to whatever current is
})
.ToList();
Then in your view, do:
#Html.DropDownListFor(m => m.PolicyID, Model.Policies, new { #class = "dropdown-field"})
Just set the PolicyID property on your view model to the value you want to be preselected:
var pm = new ManagerClass();
var po = pm.GetDataFromDb();
ViewBag.Policies = new SelectList(po, "PolicyID", "PolicyName");
viewModel.PolicyID = 7;
return View(viewModel);
Since your DropDownList is bound to the PolicyID property (m => m.PolicyID), then its value will be used when deciding which element to be preselected.
In case that you have a static menu:
1- create the following class:
public static class StaticMenus
{
public static List<string> GetGridRowsCount()
{
List<string> result = new List<string>();
result.Add("3");
result.Add("5");
result.Add("10");
result.Add("20");
result.Add("25");
result.Add("50");
result.Add("100");
return result;
}
}
2- add the following code to your controller :
ViewData["CountryList"] = new SelectList(StaticMenus.GetGridRowsCount(),"10");
3- add the following code to your view:
#Html.DropDownList("MainGridRowsCount", ViewData["RowsCountList"] as SelectList)
How do I set the selected value on a drop down list? Here is what I have so far:
#model Web.Models.PostGraduateModels.PlannedSpecialty
#Html.DropDownList("PlannedSpecialtyID")
//controller
[HttpGet]
public PartialViewResult PlannedSpecialty()
{
// Get Planned Specialty ID
var pgtservice = new PgtService();
PostGraduateModels.PlannedSpecialty plannedSpecialty = pgtservice.GetPlannedSpecialtyId();
// Get Data for Planned Specialty DropDown List from SpecialtyLookup
var pgtServ = new PgtService();
var items = pgtServ.GetPlannedSpecialtyDropDownItems();
ViewBag.PlannedSpecialtyId = items;
return PartialView(plannedSpecialty);
}
// service
public IEnumerable<SelectListItem> GetPlannedSpecialtyDropDownItems ()
{
using (var db = Step3Provider.CreateInstance())
{
var specialtyList = db.GetPlannedSpecialtyDdlItems();
return specialtyList;
}
}
// data access
public IEnumerable<SelectListItem> GetPlannedSpecialtyDdlItems()
{
IEnumerable<Specialty> specialties = this._context.Specialties().GetAll();
var selList = new List<SelectListItem>();
foreach (var item in specialties)
{
var tempps = new SelectListItem()
{
Text = item.Description,
Value = item.Id.ToString()
};
selList.Add(tempps);
}
return selList;
}
I would recommend you to avoid using ViewBag/ViewData/ Weekly typed code. Use strongly typed code and it makes it more readable. Do not use the Magic strings/ Magic variables. I would add a collection property to your ViewModel to hold the SelectList items and another property to hold the selected item value.
public class PlannedSpecialty
{
public IEnumerable<SelectListItem> SpecialtyItems { set;get;}
public int SelectedSpeciality { set;get;}
//Other Properties
}
and in your Get action, If you want to set some Item as selected,
public PartialViewResult PlannedSpecialty()
{
var pgtServ = new PgtService();
var vm=new PlannedSpecialty();
vm.SpecialtyItems = pgtServ.GetPlannedSpecialtyDropDownItems();
//just hard coding for demo. you may get the value from some source.
vm.SelectedSpeciality=25;// here you are setting the selected value.
return View(vm);
}
Now in the View, use the Html.DropDownListFor helper method
#Html.DropDownListFor(x=>x.SelectedSpeciality,Model.SpecialtyItems,"select one ")
Use the selected property of the SelectListItem class:
selList.Selected = true;