Html.GetEnumSelectList - Getting Enum values with spaces - c#

I was using asp-items="#Html.GetEnumSelectList(typeof(Salary))" in my Razor view with a select tag, to populate the list values based on the enum Salary.
However, my enum contains some items which I would like to have spaces within. E.g. one of the items is PaidMonthly, but when I display this using Html.GetEnumSelectList, I would like it to be displayed as "Paid Monthly" (with a space in it)
I tried using the Description attribute over each member in the enum, however when the select box renders it uses the raw value only.
Can anyone please help me out with this matter?
(My Code sample) -> Using ASP.NET Core 1.0
Razor View:
<select asp-for="PersonSalary" asp-items="#Html.GetEnumSelectList(typeof(Enums.Salary))">
</select>
Enum Salary:
public enum Salary
{
[Description("Paid Monthly")]
PaidMonthly = 1,
PaidYearly = 2
}

I managed to solve it. I just had to use the other method of GetEnumSelectList<>, and in the Razor view we need to use the Display attribute.
Here is the code:
Razor View:
<select asp-for="PersonSalary" asp-items="Html.GetEnumSelectList<Enums.Salary>()"></select>
Enum Salary:
public enum Salary
{
[Display(Name="Paid Monthly")]
PaidMonthly = 1,
PaidYearly = 2
}

Related

Selecting a value from a enum drop down using razor code ASP.Net MVC

I have a EnumDropDownListFor that looks like this.
#Html.EnumDropDownListFor(m => m.Countries, null, new { #class = "selectpicker" })
'selectpicker' is from this library plugin.
And countries is an enum that looks like this.
public enum Countries
{
[Display(Name = "United States")]
UnitedStates,
[Display(Name = "Afghanistan")]
Afghanistan,
}
Is there a way to make one of the enum values selected, by giving it a 'selected' attribute value via razor code?
ex. The enum is countries (United States, Mexico, Brazil, etc.) I can pass into my viewmodel either a name like 'United States', 'UnitedStates' or a index value like 3 and I want that country to get a 'selected' attribute.

Retain Enum Value after Postback MVC

View
<input type="hidden" name="selectedValue" value="0" />
<select name="itemType" id="itemType" style="width:80%;">
<option value="Item1">Item 1</option>
<option value="Item2">Item 2</option>
<option value="Item3">Item 3</option>
<option value="Item4">Item 4</option>
<option value="Item5">Item 5</option>
</select>
ViewModel
public ItemTypes itemType { get; set; }
Enum List in ItemTypes.cs (Extension Method)
public enum ItemTypes
{
Item1,
Item2,
Item3,
Item4,
Item5
}
public static string GetItemDesc(this ItemTypes itemtype)
{
switch (itemtype)
{
case ItemTypes.Item1:
return "Item 1 Description";
case ItemTypes.Item2:
return "Item 2 Description";
case ItemTypes.Item3:
return "Item 3 Description";
default:
return "Item 4 and 5 Description";
}
}
Above is my code. I would like to retain the selected Enum value throughout the page. I have four, The Index (where the drop down menu lives), the page where you select your payment method, the verification page, (where you verify all the information you put in) and the receipt page (to show that your transaction has been successful.) I need the enum value to remain the same through each page. Please help.
It looks to me like what you need to do is to save the selection somewhere, so the other pages can access that selection. MVC is stateless, so the value needs to either be passed along in each call, or it needs to be saved where the other pages can access it. There are several approaches you could take to save and retrieve selections of browser controls.
Keep in mind that enums will serialize to an integer by default, so when dealing with the value on the client-side, it will be an integer. What this means is that on your view, you likely need to use <option value="0">Item 1</option> using 0, 1, 2, 3, and 4 as your client-side values - or use the MVC HTML helpers or Razor markup, depending on your MVC version, to have those options generated for you using the enum names.
Here are some saving/retrieving options that may fit your needs:
Pass the selection value as a property of the posted content (your itemType) when you submit each page, then when you load the next page, include the value in the query string, or as part of the route for the next get request (GetPaymentMethodPage, GetVerifyPage, GetReceiptPage).
Save the selection value in a cookie, and retrieve it from that cookie in JavaScript (you'll need to provide a default if the cookie doesn't exist, was deleted, or the user doesn't allow cookies).
Save the selection value in browser storage - there are various kinds including Web Storage (SessionStorage or LocalStorage).
You have a few different options but keep in mind that MVC is stateless. This means that MVC is ignorant of any information that was stored in your enums across page requests. Therefore, you need to pass parameters into your action method that receives the enum as a string, then parse the string back into an enum type. An example of how you can do this is here.
Or the copy+pasted code:
using System;
[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
public class Example
{
public static void Main()
{
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
try {
Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);
if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
}
catch (ArgumentException) {
Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
}
}
}
}
There is also the fact that any page you want that enum to be accepted by will need to be passed the enum from the action method that generates the view. Then in the view itself, you have to accept and store the enum inside a hidden field.

Asp.net mvc3 How to display byte as string? Asp.net mvc3

I have Gender attribute as tiny int in Db for employee. When user create new employee i want him to choose male/female (which is working properly) by clicking on radio button. Everything is working fine (create and edit) but i want to display in form (for index, details and delete) not 1 or 2, but male/female. there should be some if statement in view but i'm not sure where to put it or how to write correct one ...
any idea?
Thanks!
this is part of code from model:
This one is from details.cshtml:
If you want to avoid having extra properties on your model or adding stuff to your viewbag you can write it inline using razor syntax like below..
<div class="display-field">
#if (model.GENDER == 0){ #Html.Raw("Male") }
#else if (model.GENDER == 1){ #Html.Raw("Female") }
</div>
That's off the top of my head so you might need to check the exact syntax but i think that's close. It will also just dump "Male" or "Female" inside the div, you might want to put it in a label or p tag at least.
This however isn't the approach I would use in a production app, throughout the code i would use a gender enum to give meaning to your bit value and extend enum to include a description that you can parse for presentation purposes.
I think from what u have said u can write it inline using the razor syntax like below in ur details.cshtml
<div class="display-field">
#if(model.GENDER ==0)
{
<label>Male</label>
}
else if(model.Gender==1)
{
<label>Female</label>
}
</div>
I think this must be enough for displaying the Gender in details page.plz comment if u need any help
Use a condition ? true : false selector
int gender = 1; // assumed male
String genderDesc = (gender == 1) ? "Male" : "Female";
You Could Make this a Drop Down field? In your controller do:
ViewBag.Gender = new[]
{
new SelectListItem { Text = "Male", Value = "1" },
new SelectListItem { Text = "Female", Value = "2" }
}.WithEmpty();
The WithEmpty() will give you a blank option or without it will select the top one.
#Html.DropDownListFor(m=> m.Gender, (Ienumarable<SelectListItem>)ViewBag.Gender);
This way the user will see Male and Female but the value will be bound to your model using the value which is 1 or 2.
I'd advise that you create a ViewModel class to represent the Employee entity in a View-friendly format decoupled from your database model and present it in a strongly typed view so you can return it from the controller.
Hint: Have the Gender property represented as a string in the ViewModel and do the conversion from byte to the string representation in your controller
You may put the code in your controller as e.g:
public ActionResult EmployeeDetails(int id)
{
//retrieve the entity from the DB
//set other employee properties here.
//I'm assuming you have set males to 2 and females to 1
...
employeeViewObject.Gender = employeeObjectFromDB.Gender.Value==2?"Male":"Female";
return View(employeeObjectFromDB);
}
Your strongly typed view will not have trouble displaying the gender while saving you the dirt of mixing code and mark-up as:
<p>model.Gender</p>
or
Html.DisplayFor(model=>model.Gender)

MVC3 RadioButtonFor with enum

I'm having problems with the HtmlHelper, RadioButtonFor and an enum in my model. I have a strongly typed view, and I want the checkboxes to toggle my enum property.
Enum.cs
public enum Values{
Value1,
Value2
}
Model.cs
public class Model{
public Values MyProp{ get; set; }
;
View.cshtml
#Html.RadioButtonFor(model => model.MyPropi, Values.Values1)
Controller.cs
public ActionResult WizardFirstStep()
{
var model = new Model();
return View(model);
}
If I set the MyProperty value in the controller, the RadioButton is checked as expected. But after a post to the next wizard step, which gets the model as parameter, the property isn't set.
If it will help you to understand what I mean: If it would be C# and WPF I would use a IValueConverter.
btw: I use a HtmlHelper.ActionLink to get the model to the controller.
Thanks in advance
Try this, it should work as I have done the same thing before:
#Html.RadioButtonFor(model => model.MyProp, (int)Values.Values1, model.MyProp == Values.Values1)
Notice the cast to int, it ensures the correct value is used for html.
EDIT: Sorry, I think you also need the third parameter to ensure the correct radio button is set when loading the view.
I also assumed MyPropi was a typo and changed it to MyProp, please ensure this matches up correctly at your end
Sorry for any inconvenience. After posting here, I found the solution very quickly. My ActionLink was not submitting the #Html.BeginForm form. So i changed my radiobutton to:
#Html.RadioButtonFor(model => model.MyPropi, Values.Values1, new{ onClick = "this.form.submit();" })
which submits the correct value to my controller. For the moment this is okay. Maybe the ActionLink can post back the form data.
For Aspx pages:
<%:Html.RadioButtonFor(m => m.YourProp, Selected value of your enum like : demo1.enum1.value2)

how to implement Checkboxes in MVC 3?

Hi I am quiet new on MVC 3 with C#. I am using entity framework and database first approach to generate code automatically. But the problem is, I tried to find information about inserting checkboxes in MVC3 using C# code but I could not get helpful website.
I can insert the check box using HTML tags:
<input type="checkbox" name="Science" id="s1" value="Science" />
<input type="checkbox" name="Biology" id="b1" value="Biology" />
<input type="checkbox" name="Chemistry" id="c1" value="Chemistry" />
But how do I insert the check box value inside the database and validate that only one single checkbox is selected?
e.g I have a table named Paper where I have:
Paper_Title - textbox
Paper_Details - textbox
Category - Checkboxes (e.g. Science, biology, chemistry)
Comments - textbox.
Submit-button
Use radio button and then have an enum for Categories(say enumCategories). Have a model Category of type enumCategories and then in the postback set the model based on which radio button is checked.
Hope this gives you an elaborate idea on the approach.
I don't think that checkboxes are what you need here, they're more used for multi-selectable items. Either radio buttons or a dropdown would be better suited. Personally, I'd say a dropdown is better for you as there's already an editor template built for it, example:
Model:
I have added the following to properties
public string Category { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
In the load method I have put two sample categories in there:
Categories = new List<SelectListItem>
{
new SelectListItem
{
Selected = false,
Text = "Chemistry",
Value = "Chemistry"
},
new SelectListItem
{
Selected = false,
Text = "Science",
Value = "Science"
}
};
View:
#Html.DropDownListFor(m => Model.Category, Model.Categories)

Categories

Resources