How can I localize the following enum entries on asp.net core? I found few issues on asp.net-core github repository ( https://github.com/aspnet/Mvc/pull/5185 ), but I can't find a proper way to do it.
Target enum:
public enum TestEnum
{
[Display(Name = "VALUE1_RESX_ENTRY_KEY")]
Value1,
[Display(Name = "VALUE3_RESX_ENTRY_KEY")]
Value2
}
CSHTML code block:
<select id="test" asp-items="Html.GetEnumSelectList<TestEnum>()">
</select>
Resource files:
It seems to be a bug which will be fixed in 3.0.0:
https://github.com/aspnet/Mvc/issues/7748
A server side workaround would be something like this:
private List<SelectListItem> GetPhoneStateEnumList()
{
var list = new List<SelectListItem>();
foreach (PhoneState item in Enum.GetValues(typeof(PhoneState)))
{
list.Add(new SelectListItem
{
Text = Enum.GetName(typeof(PhoneState), item),
Value = item.ToString()
});
}
return list.OrderBy(x => x.Text).ToList();
}
I created a tag helper that localizes enums, you only need to pass the enum type and a delegate for the localizing method.
<select-enum
enum-type="typeof(TestEnum)"
selected-value="(int)TestEnum.Value1"
text-localizer-delegate="delegate(string s) { return Localizer[s].Value; }"
name="testEnum">
</select-enum>
or if you are using a shared resource for localization:
<select-enum
enum-type="typeof(TestEnum)"
selected-value="(int)TestEnum.Value1"
text-localizer-delegate="delegate(string s) { return MyLocalizer.Text(s); }"
name="testEnum">
</select-enum>
install from nugget:
Install-Package LazZiya.TagHelpers -Version 2.0.0
read more here
I have the same issue. My workaround was to specify enum options explicitly:
<select asp-for="Gender" class="form-control">
<option disabled selected>#Localizer["ChooseGender"]</option>
<option value="0">#Localizer["Male"]</option>
<option value="1">#Localizer["Female"]</option>
</select>
Related
I have a dropdownlist,while editing i need to set the current value.But my codes are not working.
My view look like follow
#Html.DropDownListFor(m => m.id, Model.ddls, "Please Select", new { #class = "form-control" })
Model
public string id { get; set; }
public List<SelectListItem> ddls { get; set; }
Controller
public IActionResult editmaster(string id, string sec)
{
master m = new master();//here is my model
m.ddls = PopulateDDLDataSet(ds.Tables[1], "companyname", "companyid");//ddls is my object and populateddldataset is my methode to fill the list
return View(m);
}
ddls is the selectedlistitems that i have filled from controller,that work fine.But the value which in in id not set on the list
Checked the code and its working for me. Could you provide more details about your model?
Wanted to say that you can make similar things by using built-in razor tag helpers that is more clear.
Documentation for select
Example of using tag helper in your code:
<select class="form-control" asp-for="#Model.id" asp-items="Model.ddls">
<option selected>Please select</option>
</select>
please follow this, it may be this code help you.
Model Code
public class testmdl
{
public string id { get; set; }
public IEnumerable<SelectListItem> ddls { get; set; }
}
Controller Code
//------ without using entity for select list items
public IActionResult Test()
{
testmdl obj=new testmdl();
IEnumerable<SelectListItem> companyList = new List<SelectListItem>
{
new SelectListItem { Value = "001", Text = "StackOverflow1" },
new SelectListItem { Value = "002", Text = "StackOverflow2" }
};
obj.ddls =companyList ;
return View(obj);
}
//--- using entity framework for select list items
public IActionResult Test()
{
testmdl obj=new testmdl();
List<SelectListItem> companyList = new SelectList(db.yourcompanytable, "companyid", "comapnyname").ToList();
obj.ddls =companyList ;
return View(obj);
}
View Code
<select id="id1" name="id1" asp-for="id" asp-items="#Model.ddls" class="form-control">
<option value=#null>--- Select --- </option>
</select>
<span asp-validation-for="id" style="color:red;"></span>
In my case none of the above answers work(I don't clearly understand what went wrong for me) ,but finally i achieved in an alternative way.Below my codes.Thanks for all the supports.
<script>
document.getElementById("id").value =#Model.id;
</script>
Put this after binding the dropdownlist.
I have one dropdown in my MVC application.
I have a field in my model:
public IList<SexGenderModel> SexualOrientationList { get; set; }
class for SexGenderModel:
public class SexGenderModel
{
public int? MasterID { get; set; }
public string CodeDescription { get; set; }
public string SNOMED { get; set; }
}
In my view page I have used razor syntax
#Html.DropDownListFor(x => x.SexualOrientationList, new SelectList(Model.SexualOrientationList, "MasterID", "CodeDescription"), "--Select--", new { #class = "form-control input-sm"})
Every list item has their own SNOMED which I want to display in tooltip.
Please note I want to display tooltip for ListItem not for selected item of dropdown.
How can I achieve this with razor?
Any other option to map attributes to dropdownlist(Model.SexualOrientationList) from backend? How?
All you need to add attribute "title" to each item in dropdown
<select>
#foreach (var item in Model.SexualOrientationList)
{
<option title='#item.SNOMED' value="#item.MasterID">#item.CodeDescription</option>
}
</select>
Going further with #Khaled-Yosry 's answer:
#Ankita this DOES use Razor, so I'm not sure why you find yourself restricted.
If it's the <select> tag rendering you are worried about, you can append the necessary tags yourself:
All you need to add attribute "title" to each item in dropdown
<select name="#Html.NameFor(m => m.SexualOrientation)" id="#Html.IdFor(m => m.SexualOrientation)" class="form-control input-sm">
<option value="">--Select one--</option>
#foreach (var item in Model.SexualOrientationList)
{
<option title="#item.SNOMED" value="#item.MasterID" #(Model.SexualOrientation == item.MasterID ? "selected" : string.empty)>#item.CodeDescription</option>
}
</select>
Also, don't forget to include a property in your Model which will actually be bound to the selected value of the dropdown list:
public int SexualOrientation { get; set; }
I have asp web form and i'm using razor technique to post that form,
problem is that, i want to know that how to specify ID and NAME attribute to razor dropdown list because, in next step, i'm getting the form value by using the ID and NAME attribute..
VIEW code is :
#Html.DropDownList("ID", (SelectList) ViewBag.list, " -- Select Business Type -- ")
CONTROLLER:
public ActionResult coverage()
{
var query = db.Database.SqlQuery<businessDropDownModel>("businesDropDownSP");
ViewBag.list = new SelectList(query.AsEnumerable(), "ID", "BusinessTypeName", "----select----");
return View();
}
MODEL:
public class businessDropDownModel
{
public int ID { set; get; }
public string BusinessTypeName { set; get; }
}
If you want to set the name and id or other attributes you can use the html attributes option.
NOTE: the method has a quirk: you can use the attributes dictionary to override the "id", but not the "name".
example:
#Html.DropDownList("Selected", Model.SelectList, "First Option", new { name = "Name", id = "id"})
will render:
<select id="id" name="Selected">...</select>
So the upshot is: if you want name and id to be different, set the name parameter to what you want the name to be, and use the dictionary to override the id.
The first argument in #Html.DropDownList("MyIdAndName", (SelectList) ViewBag.list, " -- Select Business Type -- ") is both the id and the name of the select tag.
So,
#Html.DropDownList("MyIdAndName", (SelectList) ViewBag.list, " -- Select Business Type -- ")
would render
<select id="MyIdAndName" name="MyIdAndName">...</select>
If you need to set the Id to something different than the Name, you can use the htmlAttributes parameter to set the Id of the control. You still use the first parameter in the DropDownList helper to set the Name of the control.
#Html.DropDownList( "Job.DefaultProfitCenter", (SelectList)ViewBag.DefaultProfitCenter, " -- Select -- ", new { id = "Job_DefaultProfitCenter" } )
This will generate the following html for the drop down list:
<select id="Job_DefaultProfitCenter" name="Job.DefaultProfitCenter">
<option value=""> -- Select -- </option>
<option value="0">Option 1</option>
</select>
I want to set first option value to 0 instead leaving it blank. How can I set this?
i.e
<select id="PatentId" name="ParentId">
<option value="0">--Select--</option>
<option value="1">Books</option>
// other options
</select>
My code is as
<div class="editor-field">
#Html.DropDownList("ParentId","--Select--")
#Html.ValidationMessageFor(model => model.ParentId)
</div>
You can't do this with the built-in helper. You will have to write a custom helper or hardcode or whatever.
Or simply use a view model and a nullable integer:
[Required]
public int? ParentId { get; set; }
Now you will no longer have any problems or needs to use 0 as first option.
Also it is better to use the strongly typed version of the helper:
#Html.DropDownListFor(model => model.ParentId, Model.Parents, "--Select--")
But if for some other reason (which I don't see at the moment) you need to use 0 as first option you are on your own in the wilderness.
Finally I found the following code working
private SelectList AddFirstItem(SelectList list)
{
List<SelectListItem> _list = list.ToList();
_list.Insert(0, new SelectListItem() { Value = "0", Text = "--Select--" });
return new SelectList((IEnumerable<SelectListItem>)_list, "Value", "Text", list.SelectedValue);
}
Keep the "Value" and "Text". The Last one list.SelectedValue is to keep selected values as it is.
You can use the above function like
public ActionResult Create()
{
ViewBag.ParentId = AddFirstItem(new SelectList(db.Categories, "Id", "Name"));
return View();
}
It worked.
I want to create a DropDownList with a binding for one of my model data, but i want the dropdown items to be built within the View and i do not want the items coming in the Model data or from my controller. Can you please suggest how to build the selectlist within View
Basically I want to create something like this:
<%= Html.DropDownListFor(model=>model.SomeProperty,<<create the dropdown list items here>> %>
Please suggest.
-Sampat.
You can't use it that way. As the name suggests its for returning an HTML select element for each property in the object that is represented by the specified expression using the specified list items and HTML attributes.
Though you can create this list object in view like following :-
#Html.DropDownListFor(model => model.DropDownElement,
new SelectList(model.DropDownElement, "Id", "Name"))
Update
I will take the example of a Country Model with an Id/Name pair. Like following
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
Now, in your controller action, you can pass it as a selectlist:
public ActionResult YourAction()
{
YourModel yourModel = new YourModel(); // Just for reference. I suppose you must be passing some model to your view
ViewBag.DropDownList = new SelectList(db.Countries, "Id", "Name"); // This way you don't need to make any changes with your passing model.
return View(yourModel);
}
And finally in View, you can use the DropDownListFor in the following manner.
#Html.DropDownListFor(model => model.YourModelProperty,
(IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---")
On a Sidenote, if you just want to display a list of numbers with value, you can directly enter the HTML and utilize it, rather than using the DropDownListFor. Like follwing
<select id="yourModelPropertyName" name="yourModelPropertyName">
<option value="">---Select Value---</option>
<option value="1">India</option>
<option value="2">Australia</option>
<option value="3">US</option>
<option value="4">England</option>
<option value="5">Finland</option>
</select>
Just make sure that "yourModelPropertyName" is correct and it should be the one for the property where you want it updated
More update
In the views where you wan't to show the selected value, use below code
<select id="yourModelPropertyName" name="yourModelPropertyName">
<option selected="selected" value="1">#model.YourDropDownList</option>
<option value="2">India</option>
<option value="3">Australia</option>
</select>
This shall do the trick :-)
#Pankaj gave you a rough way of doing it. You can also pass the IEnumerable of SelectListItem object tobject to your view from controller and create your select element based on that.
Here is a good example:
A Way of Working with Html Select Element (AKA DropDownList) In ASP.NET MVC
Imagine that your controller looks like something like this:
public ActionResult Index() {
var products = productRepo.GetAll();
registerProductCategorySelectListViewBag();
return View(products);
}
private void registerProductCategorySelectListViewBag() {
ViewBag.ProductCategorySelectList =
productCategoryRepo.GetAll().Select(
c => new SelectListItem {
Text = c.CategoryName,
Value = c.CategoryId.ToString()
}
);
}
on your view, DropDownListFor html helper should look like something like this:
#Html.DropDownListFor(m => m.CategoryId,
(IEnumerable<SelectListItem>)ViewBag.ProductCategorySelectList
)