how to convert Enum to IEnumerable<SelectListItem> - asp.net-mvc-2

UPDATE 1
I want to populate a listboxfor mvc helper to render list items in View. I don't know how to pass the second parameter to the helper, which accepts IENumerableSelectListItem SelectionList.
Html.ListBoxFor(model => model.SelectedDate, Model.DateList, new { })
I am having a property in my model class,
public IEnumerableSelectListItem DateList { get; set; }
and somehow i need to populate DateList from my controller action method, which fills up all the other model properties and passes it to a partial view where i have the helper. DateList should be getting the values from an Enum DateListEnum
Any ideas on how to go about doing this. Also let me know how do i ensure that a single list item is selected at a time...i am really new to all these..and its been quite some time i am working on this...but nothing came up so far....
I am having below code in my controller action method,
model.DateList = getDateList();
which calls this method,
public IEnumerableSelectListItem getDateList()
{
IEnumerableSelectListItem values = Enum.GetValues(typeof(DateListEnum));
//this one doesn't work because of casting issues and this is where i want to convert Enum Values to IEnumerableSelectListItem
return values;
}
UPDATE 2
i have the listbox working and its displaying in the UI based upon below code
` IEnumerable<SelectListItem> values = Enum.GetNames(typeof(ColumnFormattingDateFormats)).Cast<ColumnFormattingDateFormats>().Select(p => new SelectListItem()
{
Text = p.ToString(),
Value = ((int)p).ToString()
}).ToList();`
But now i am having few other problems,
the enum that i am using is
`public enum ColumnFormattingDateFormats : int
{
[StringValue("Wednesday, March 14, 2001")]
FULLDATE = 0,
[StringValue("3/14")]
MMDDWSLASH = 1,
[StringValue("3/14/01")]
MMDDYYWSLASH = 2,
[StringValue("03/14/01")]
MMDDYYWMMZEROPREFIXWSLASH = 3
}`
and my helper looks like this,
Html.ListBoxFor(model => model.SelectedDate, Model.DateList, new { })
1> How do i pass the selected item to the listboxfor helper?
is there a way to pass the selected item to the helper through the property
[DataMember]
public ColumnFormattingDateFormats SelectedDate{ get; set; }
in my model class? to begin with i am passing
this.SelectedDate= ColumnFormattingDateFormats.FULLDATE;
to the default constructor in my model class...but for some reason the first parameter model => model.SelectedDatehas some problem with that..throws null exception...
2> how do i ensure [StringValue] from Enum gets displayed in UI listbox element and not the Enum Text for ex. FULLDATE should not be getting displayed, instead "Wednesday, March 14, 2001" should be?
3> How do i ensure that a single item is selected without using livequery?
My brains are all fried up now....any directions anyone?????

how about:
Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Select(p => new SelectListItem()
{
Text = p.ToString(),
Value = ((int) p).ToString()
})
.ToList();

Related

Formatting dates in an MVC Dropdown

I have a dropdown list on my page as so: -
#Html.DropDownList("dd_dates", new SelectList(#Model.seasonDates), "Please Select")
where seasonDates is an IList of dates. The problem is that when the dates are displayed in the dropdown they also have the time on them as well. How do I format the display date so that the time is not included.
Maybe a better way to do this would be to define a property in your model that returns IEnumerable<SelectListItem> (in your model class):
public DateTime SelectedDate {get;set;}
public IEnumerable<SelectListItem> SeasonDates
{
get
{
foreach (var item in seasonDates)
yield return new SelectListItem()
{
Text = item.ToShortDateString(), // or apply your own formatting!
Value = item
};
}
}
Then use this in the view:
#Html.DropDownListFor(m => m.SelectedDate, #Model.SeasonDates, "Please Select")
Apologies if there are errors, I dont have VS open to verify the sytanx.

How to save the selected value from dropdownlist to database using Entity Framework in ASP.NET MVC 4

In my one of the view I add a dropdown and I bind this drop down with my database like this..
public ActionResult PostMarks()
{
JoinMod std = new JoinMod();
std.Drp_bind = (from nm in db.TbStudent
select new SelectListItem
{
Text = nm.StudentName,
Value = SqlFunctions.StringConvert((double)nm.StudentId).Trim()
}).ToList<SelectListItem>();
return View(std);
}
Here is the dropdownlist in my view
<p>StudentName</p>
#Html.DropDownList("StudentName",Model.Drp_bind,"Select")
And on Post I am trying to save the data into the database like this
[HttpPost]
public ActionResult PostMarks(Marks marks)
{
db.TbMarks.Add(marks);
db.SaveChanges();
return RedirectToAction("ShowAllMarks");
}
Now when I check my database after save data in database the Id save in the database is zero from the dropdownlist. Please experts help me to solve this issue
You should be using #HTML.DropDownListFor, specifying a lambda that indicates which property in your model you want to bind the list's selected value to on the POST.
Given a view model like so:
public class MarksViewModel
{
public Marks Marks { get; set; }
public IEnumerable<SelectListItem> Drp_bind { get; set; }
}
The drop down list in the CSHTML can be declared like so:
#Html.DropDownListFor(m => m.Marks.StudentId, m.Drp_bind, "Select a Student")
The first argument is an expression describing the property on your model that you want to populate with the selected value from the drop down list in the post back. The second is the list comprising the values to which we need to data bind.
Note that your CSHTML will need more form fields within it bound to the other properties of the Marks property.
Your POST method would now take MarksViewModel as an argument and extract the Marks property from it to add to the DbContext for saving.

retrieve values from model in mvc2

I don't know how to create functions to retrieve the values.
*Table 1: OrgVasplans*
-Id
-vasplanId
-OrgId
-CreatedDate
Table-2: vasplans
-Id
-name
-amount
-validity
-vasdurationId
Table-3: VasDuration
Id
Duration.
These are my tables..
I have Controller named Candidatesvas and action method VasDetails....
I already stored the values into vasPlans table.
when I click in view "Details" link it will go to details page..
Then the values are retrieve from "Orgvasplans" table automatically without enter any input..
How to create methods for this....
I created some methods but the method contains only Name "field". I want to retrieve multiple values like "Amount", "validity" like that.....
Repository:
public IQueryable<VasPlan> GetVasPlans()
{
return from vasplan in _db.VasPlans
orderby vasplan.Name ascending
select vasplan;
}
public OrgVasPlan GetOrgVasPlan(int id)
{
return _db.OrgVasPlans.SingleOrDefault(v => v.Id == id);
}
public int AddOrgVasPlan(OrgVasPlan orgvasplan)
{
_db.OrgVasPlans.AddObject(orgvasplan);
Save();
return orgvasplan.Id;
}
public void AddVasPlan(VasPlan vasPlan)
{
_db.VasPlans.AddObject(vasPlan);
}
Controller
public ActionResult VasDetails(FormCollection collection)
{
OrgVasPlan orgvasplan = new OrgVasPlan();
orgvasplan.CreatedDate = DateTime.Now;
orgvasplan.OrgId = LoggedInOrganization.Id;
orgvasplan.vasplanId=??????????????
VasPlan vasplan = new VasPlan();
//if (!string.IsNullOrEmpty(collection["Name"])) ;
_repository.AddOrgVasPlan(orgvasplan);
_repository.Save();
return View();
}
Here i don't know how to put code here for get multiple values form vasplans table like(amount,name,validity etc...,)
this is my problem...
Make your view strongly-typed, make sure you create input elements whose names correspond to the model properties (or use HTML helpers, e.g. Html.TextBoxFor(model => model.Amount). That way MVC will automatically fill in the model for you when the action that should take the model as a argument, is invoked.
For example your action should be:
public ActionResult NewVasPlan(VasPlan vplan)
{
//check model state
//save or return error messages
}
Or you can simply add string and int parameters to the Action like this:
public ActionResult NewVasPlan(string name, int amount /*, etc*/)
{
//MVC will also automatically fill name, amount, from request POST or GET params
//(or cookies??)
}
Hope this helps, tell me if you need more info or if I misunderstood your question.

DropDownList does not get selected using with HtmlHelper.DropDownListFor

I render a dropdown list to allow the user to select the enum value using this solution http://blogs.msdn.com/b/ukadc/archive/2010/06/22/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx.
this is the helper
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
IEnumerable<SelectListItem> items =
values.Select(value => new SelectListItem
{
Text = CultureLocalizationHelper.GetString(value.ToString(), typeof(SiteResources.Core.Views.CulturalConfiguration.Index)),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
});
return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}
This approach works very well with any enum but not with this
public enum Color
{
Orange = 1,
Green = 2,
Blue = 3,
Primary = 4
}
I have a very weird problem, the helper does not work with this enum.
I debug the SelectListItems and there's one that is selected but DropDownListFor does not render any of the elements with selected="selected"
Any idea?
Thanks for your time!
specify a new SelectList(values, selectedValue) instead of specifying the SelectListItems directly to set the selected value
<%: Html.DropDownListFor(model=> model.Type, new SelectList(Enum.GetValues(typeof(UserType)), (Model??new User()).Type)) %>
One way is to overload an Enum ToString() and/or create your own Attribute as described in http://lostinloc.com/2008/05/06/c-overloading-an-enums-tostring/.

Using ListBoxFor in ASP.NET MVC 2

I am trying to update the Roles a specific group has in my application. The Group model I use in my view has an additional AllRoles IEnumerable attached to it, so that in my view I can do something like this:
<%: Html.ListBoxFor( model => model.aspnet_Roles, new MultiSelectList( Model.AllRoles, "RoleId", "RoleName" ), new { #class = "multiselect" } )%>
This generates a multiple select drop down as expected. However, coming form PHP, I noticed that the name of the select was without square brackets, maybe that is OK in ASP.NET but in PHP it is wrong.
Now, how do I go about updating the group after submiting the form, more precisely, how can I read the multiselct selected values. What I need is that based on the RoleIds that I receive to Add respective aspnet_Roles to my Group model.
Trying to read the received values using HttpContext.Request.Form["aspnet_Roles"] failed and is also ugly. Can I somehow use the model to fetch the needed data? Controller function:
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Edit( SYSGroups updatedGroup ) {}
Thanks
The selected ids will be sent as a collection:
[HttpPost]
public ActionResult Edit(string[] aspnet_Roles)
{
// the aspnet_Roles array will contain the ids of the selected elements
return View();
}
If the form contains other elements that need to be posted you could update your model:
public class SYSGroups
{
public string[] Aspnet_Roles { get; set; }
... some other properties
}
and have your action method look like this:
[HttpPost]
public ActionResult Edit(SYSGroups updatedGroup)
{
// updatedGroup.Aspnet_Roles will contain an array of all the RoleIds
// selected in the multiselect list.
return View();
}