Trouble filling and using MultiSelectList/ListBoxFor in ASP.NET MVC 3 - asp.net-mvc-3

I'm trying to adapt the answers for filling a ListBoxFor that has preselected values that I've found here on SO and am having some trouble with the adaptation.
This is one of the questions I've been referring to: here
Here is my class that defines a list object
public class SelectListDTO {
public int ID { get; set; }
public string Name { get; set; }
}
I have a method on a class that fills a List of SelectListDTO items. The CheckRefresh checks to see if the cache is expired, if so it refills the cache. So this method gets my list:
private List<SelectListDTO> GetSelectList() {
CheckRefresh();
var lst = new List<SelectListDTO>(_cache.Count + 1);
_cache.ForEach(item => lst.Add(new SelectListDTO { ID = item.ID, Name = item.Name }));
return lst;
}
My Model is define with these Properties/Methods:
public class MyModel {
[Required]
[Display(Name = "Program Type")]
[Min(1, ErrorMessage = "Please select a Program Type")]
public int[] SelectedProgramTypes { get; set; }
public MultiSelectList ProgramTypes { get; set; }
public MyModel() {
PopulateProgramTypeList();
}
private void PopulateProgramTypeList() {
// Get all available list items
var programTypes = ProgramTypeService.Instance.GetSelectList;
// how to fill multiselectlist with my List<SelectListDTO> items;
ProgramTypes = new MultiSelectList(??)
}
}
1st part of question is from above here^ How to fill the MultiSlectList with my List of SelectListDTO objects
Also in my controller action I am getting the saved items from the DB and will need to pass them to the model as SelectedProgramTypes. This is currently in my action:
public ActionResult Edit(int? id) {
// Code here to validate id and that user is associated with id
lenderProduct = new LenderProduct(id);
var model = BuildModel(lenderProduct); // returns instance or MyModel
var selectedProgramTypes = lenderProduct.ProgramTypes;
foreach (var item in selectedProgramTypes) {
/// How to fill the Model.SelectedProgramTypes array
}
return View(model);
}
2nd part of question is how to get the currently selected items that I read from the DB into the array that can be used by the MultiSelectList in the Model
I feel like I'm this close but am missing some pattern or hopefully just the correct syntax into getting this to work in this way as opposed to the ways I've seen posted here.
I haven't made it to the View yet but from what I've seen that is just as easy as filling a normal DropDownList.

1st part of question is from above here^ How to fill the
MultiSlectList with my List of SelectListDTO objects
ProgramTypes = new MultiSelectList(programTypes.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Name
}));
2nd part of question is how to get the currently selected items that I
read from the DB into the array that can be used by the
MultiSelectList in the Model
It's not clear how your LenderProduct class looks like but assuming the ProgramTypes property is just an array of integers you could directly assign it to your view model:
public ActionResult Edit(int? id)
{
// Code here to validate id and that user is associated with id
var lenderProduct = new LenderProduct(id);
var model = BuildModel(lenderProduct); // returns instance or MyModel
model.SelectedProgramTypes = lenderProduct.ProgramTypes;
return View(model);
}
and if it is an array of some complex object you could select the corresponding property that contains the id:
public ActionResult Edit(int? id)
{
// Code here to validate id and that user is associated with id
var lenderProduct = new LenderProduct(id);
var model = BuildModel(lenderProduct); // returns instance or MyModel
model.SelectedProgramTypes = lenderProduct.ProgramTypes.Select(x => x.ID).ToArray();
return View(model);
}

Related

Getting carousel data back into object

I am creating a dynamic carousel view in my Xamarin app, and so far it works just fine, but...
My carousel contains students and each carousel page is a link to a student info page. I want to be able to set an object with the current selected student for me to grab on all the students subpages (hope this makes sense :-/).
My script is as follow.
StudentModel:
public class StudentData
{
public string id { get; set; }
public string name { get; set; }
public string course { get; set; }
public string schoolclass { get; set; }
public string profileImage { get; set; }
}
CarouselPart:
ObservableCollection<StudentData> collection = new ObservableCollection<StudentData>();
collection.Add(new StudentData { name = "Soren Hanson", schoolclass = "4. grade", course = "Math" });
collection.Add(new StudentData { name = "Michael Trane", schoolclass = "7. grade", course = "English" });
collection.Add(new StudentData { name = "Tammy Jump", schoolclass = "1. grade", course = "English" });
DataTemplate template = new DataTemplate(() =>
{
var imageBtn = new Button();
imageBtn.Image = "Images/default.png";
imageBtn.Clicked += delegate {
// ADDING THE CURRENT STUDENT TO MY CURRSTUDENT OBJECT //
//App.currStudent = collection.......
var menteeOptions = new MenteeOptions();
imageBtn.Navigation.PushAsync(menteeOptions);
}
}
carousel.ItemTemplate = template;
carousel.PositionSelected += pageChanged;
carousel.ItemsSource = collection;
Hoping for help with this and thanks in advance :-)
Well you question was quite confusing at first but I will answer it from what I understood you want to keep the selected student object with you on your subpages:
So you can either use SQLite for it which can be found here
Or you can just maintain it as a static system object on your app.xaml.cs and use it
Something like this
App.Xaml.cs
public static object YourDataHolder {get; set;}
In your clicked event:
imageBtn.Clicked += delegate {
// ADDING THE CURRENT STUDENT TO MY CURRSTUDENT OBJECT //
App.YourDataHolder = _yourCollection;
var menteeOptions = new MenteeOptions();
imageBtn.Navigation.PushAsync(menteeOptions);
}
The use it something like this :
fooObject=App.YourDataHolder as FooType;

MVC populate dropdown from foreign key

I have been struggling with this for several days. I need to populate a dropdownlistfor with genres.
My MovieRepository to grab the genres:
public IQueryable<Movies> MoviesAndGenres
{
get { return db.Movies.Include(m => m.parentGenre); }
}
My movie model
public virtual Genres parentGenre { get; set; }
Genre Model:
public class Genres
{
public Genres()
{
this.movies = new HashSet<Movies>();
}
[Key]
public int genreId { get; set; }
[Required(ErrorMessage = "A genre name is required")]
[StringLength(25)]
public String genreName { get; set; }
public ICollection<Movies> movies { get; set; }
}
I am trying to pass in the genres with a select list, but I am getting a LINQ to Entities does not recognize the System.String To String() Method, and this method cannot be translated to a stored expression.
Movies Controller, addMovie action:
ViewBag.Genres = movieRepository.MoviesAndGenres.Select(m => new SelectListItem
{
Text = m.parentGenre.genreName,
Value = m.parentGenre.genreId.ToString()
}).ToList();
return View();
View:
#Html.DropDownListFor(m => m.parentGenre, (SelectList)ViewBag.Genres)
Any help would be greatly appreciated!
Update:
Repository:
public IQueryable<Genres> MoviesAndGenres
{
get { return db.Genres; }
}
Controller:
var x = movieRepository.MoviesAndGenres.Select(m => new
{
Text = m.genreName,
Value = m.genreId
});
ViewBag.Genres = new SelectList(x);
return View();
View:
#Html.DropDownListFor(m => m.parentGenre, (SelectList)ViewBag.Genres)
Since you're retrieving all of the records anyways, you can just do this.
ViewBag.Genres = movieRepository.MoviesAndGenres.AsEnumerable()
.Select(m => new SelectListItem
{
Text = m.parentGenre.genreName,
Value = m.parentGenre.genreId.ToString()
});
You would also need to change your view to:
#Html.DropDownListFor(m => m.parentGenre, new SelectList(ViewBag.Genres))
Actually, a better approach would probably be this, since then it only retrieves the specific columns you need:
var x = movieRepository.MoviesAndGenres.Select(m => new
{
Text = m.parentGenre.genreName,
Value = m.parentGenre.genreId
});
ViewBag.Genres = new SelectList(x)
Also, the ToList() is no longer required because it's already in a an immediate state.

Unable to cast object of type WhereSelectListIterator

I have been attempting to figure out why a Linq query that returns a list of U.S. States formatted for a drop down list will not cast to a List when the code returns to the calling method. The error that I get is:
Unable to cast object of type 'WhereSelectListIterator'2[StateListing.States,<>f__AnonymousTypea'2[System.String,System.String]]' to type 'System.Collections.Generic.List`1[StateListing.States]'
The namespace StateListing from the error, is a dll library that has a class called States returning an IEnumerable List of states shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StateListing
{
public class States
{
public string StateAbbriviation { get; set; }
public int StateID { get; set; }
public string StateName { get; set; }
static int cnt = 0;
public static IEnumerable<States> GetStates()
{
return new List<States>
{
new States
{
StateAbbriviation = "AL",
StateID=cnt++,
StateName = "Alabama"
},
new States
{
StateAbbriviation = "AL",
StateID=cnt++,
StateName = "Alaska"
}
//Continued on with the rest of states
}.AsQueryable();
}
}
}
In my control I make a call to GetStates that returns a List of States from the class library above.
[HttpPost]
public JsonResult GetStateOptions()
{
try
{
//Return a list of options for dropdown list
var states = propertyRepository.GetStates();
return Json(new { Result = "OK", options = states });
}
In the property repository class I have two methods one to get the StateList from the library, and another to format the listing of states for a drop down list in my view.
public List<States> GetStateList()
{
var items = (from s in States.GetStates()
select s).ToList();
return items;
}
List<States> IPropertyRepository.GetStates()
{
try
{
List<States> RawStates = GetStateList();
var stateList = RawStates.Select(c => new { DisplayText = c.StateName, Value = c.StateID.ToString() });
return (List<States>)stateList; //<=== Error
}
The error occurs when the code reaches the return within the GetStates method.
Any help with this casting problem explaining what I'm doing wrong would be appreciated.
This is the problem:
var stateList = RawStates.Select(c => new { DisplayText = c.StateName,
Value = c.StateID.ToString() });
return (List<States>)stateList;
Two issues:
Select doesn't return a List<T>
You're not= selecting States objects; you're selecting an anonymous type
The first is fixable using ToList(); the second is fixable either by changing your Select call or by changing your method's return type. It's not really clear what you really want to return, given that States doesn't have a DisplayText or Value property.
I would expect a method of GetStates to return the states - in which case you've already got GetStatesList() which presumably does what you want already.
Basically, you need to think about the type you really want to return, and make both your method return type and the method body match that.
You are projecting your LINQ query to an anonymmous object and not to a State list which obviously cannot work. The 2 types are incompatible. So start by modifying your repository layer and get rid of the GetStateList method:
public class PropertyRepository: IPropertyRepository
{
public List<States> GetStates()
{
return States.GetStates().ToList();
}
}
and then project to the desired structure in your controller:
[HttpPost]
public JsonResult GetStateOptions()
{
var states = propertyRepository.GetStateList();
var options = states.Select(x => new
{
DisplayText = c.StateName,
Value = c.StateID.ToString()
}).ToList();
return Json(new { Result = "OK", options = states });
}

Edit on Model - complex types not updated properly

I have this two objects - Magazine and Author (M-M relationship):
public partial class MAGAZINE
{
public MAGAZINE()
{
this.AUTHORs = new HashSet<AUTHOR>();
}
public long REF_ID { get; set; }
public string NOTES { get; set; }
public string TITLE { get; set; }
public virtual REFERENCE REFERENCE { get; set; }
public virtual ICollection<AUTHOR> AUTHORs { get; set; }
}
public partial class AUTHOR
{
public AUTHOR()
{
this.MAGAZINEs = new HashSet<MAGAZINE>();
}
public long AUTHOR_ID { get; set; }
public string FULL_NAME { get; set; }
public virtual ICollection<MAGAZINE> MAGAZINEs { get; set; }
}
}
My problem is that I can't seem to update the number of authors against a magazine e.g. if I have 1 author called "Smith, P." stored already against a magazine, I can add another called "Jones, D.", but after the post back to the Edit controller the number of authors still shows 1 - i.e. "Smith, P.H".
Please not that I have successfully model bound the number of authors back to the parent entity (Magazine), it uses a custom model binder to retrieve the authors and bind to the Magazine (I think), but it still doesn't seem to update properly.
My code for updating the model is straight forward - and shows the variable values both before and after:
public ActionResult Edit(long id)
{
MAGAZINE magazine = db.MAGAZINEs.Find(id);
return View(magazine);
}
and here are the variables pre-editing/updating -
[HttpPost]
public ActionResult Edit(MAGAZINE magazine)
{
if (ModelState.IsValid)
{
db.Entry(magazine).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(magazine);
}
...and here are the variables after a new author has been added...
I am getting suspicious that the author entity is showing, post edit that it is not bound to any magazine and I am guessing this is why it is not being updated back to the magazine entity - but it is perplexing as I am effectively dealing with the same magazine entity - I guess it may be something to do with the custom model binder for the author.
Can anyone help on this matter?
For completeness - I have included my AuthorModelBinder class too -
public class AuthorModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (values != null)
{
// We have specified asterisk (*) as a token delimiter. So
// the ids will be separated by *. For example "2*3*5"
var ids = values.AttemptedValue.Split('*');
List<int> validIds = new List<int>();
foreach (string id in ids)
{
int successInt;
if (int.TryParse(id, out successInt))
{
validIds.Add(successInt);
}
else
{
//Make a new author
AUTHOR author = new AUTHOR();
author.FULL_NAME = id.Replace("\'", "").Trim();
using (RefmanEntities db = new RefmanEntities())
{
db.AUTHORs.Add(author);
db.SaveChanges();
validIds.Add((int)author.AUTHOR_ID);
}
}
}
//Now that we have the selected ids we could fetch the corresponding
//authors from our datasource
var authors = AuthorController.GetAllAuthors().Where(x => validIds.Contains((int)x.Key)).Select(x => new AUTHOR
{
AUTHOR_ID = x.Key,
FULL_NAME = x.Value
}).ToList();
return authors;
}
return Enumerable.Empty<AUTHOR>();
}
}
I faced a very similar scenario when I developed my blog using MVC/Nhibernate and the entities are Post and Tag.
I too had an edit action something like this,
public ActionResult Edit(Post post)
{
if (ModelState.IsValid)
{
repo.EditPost(post);
...
}
...
}
But unlike you I've created a custom model binder for the Post not Tag. In the custom PostModelBinder I'm doing pretty much samething what you are doing there (but I'm not creating new Tags as you are doing for Authors). Basically I created a new Post instance populating all it's properties from the POSTed form and getting all the Tags for the ids from the database. Note that, I only fetched the Tags from the database not the Post.
I may suggest you to create a ModelBinder for the Magazine and check it out. Also it's better to use repository pattern instead of directly making the calls from controllers.
UPDATE:
Here is the complete source code of the Post model binder
namespace PrideParrot.Web.Controllers.ModelBinders
{
[ValidateInput(false)]
public class PostBinder : IModelBinder
{
private IRepository repo;
public PostBinder(IRepository repo)
{
this.repo = repo;
}
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
// retrieving the posted values.
string oper = request.Form.Get("oper"),
idStr = request.Form.Get("Id"),
heading = request.Form.Get("Heading"),
description = request.Form.Get("Description"),
tagsStr = request.Form.Get("Tags"),
postTypeIdStr = request.Form.Get("PostType"),
postedDateStr = request.Form.Get("PostedDate"),
isPublishedStr = request.Form.Get("Published"),
fileName = request.Form.Get("FileName"),
serialNoStr = request.Form.Get("SerialNo"),
metaTags = request.Form.Get("MetaTags"),
metaDescription = request.Form.Get("MetaDescription"),
themeIdStr = request.Form.Get("Theme");
// initializing to default values.
int id = 0, serialNo = 0;
DateTime postedDate = DateTime.UtcNow;
DateTime? modifiedDate = DateTime.UtcNow;
postedDate.AddMilliseconds(-postedDate.Millisecond);
modifiedDate.Value.AddMilliseconds(-modifiedDate.Value.Millisecond);
/*if operation is not specified throw exception.
operation should be either'add' or 'edit'*/
if (string.IsNullOrEmpty(oper))
throw new Exception("Operation not specified");
// if there is no 'id' in edit operation add error to model.
if (string.IsNullOrEmpty(idStr) || idStr.Equals("_empty"))
{
if (oper.Equals("edit"))
bindingContext.ModelState.AddModelError("Id", "Id is empty");
}
else
id = int.Parse(idStr);
// check if heading is not empty.
if (string.IsNullOrEmpty(heading))
bindingContext.ModelState.AddModelError("Heading", "Heading: Field is required");
else if (heading.Length > 500)
bindingContext.ModelState.AddModelError("HeadingLength", "Heading: Length should not be greater than 500 characters");
// check if description is not empty.
if (string.IsNullOrEmpty(description))
bindingContext.ModelState.AddModelError("Description", "Description: Field is required");
// check if tags is not empty.
if (string.IsNullOrEmpty(metaTags))
bindingContext.ModelState.AddModelError("Tags", "Tags: Field is required");
else if (metaTags.Length > 500)
bindingContext.ModelState.AddModelError("TagsLength", "Tags: Length should not be greater than 500 characters");
// check if metadescription is not empty.
if (string.IsNullOrEmpty(metaTags))
bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Field is required");
else if (metaTags.Length > 500)
bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Length should not be greater than 500 characters");
// check if file name is not empty.
if (string.IsNullOrEmpty(fileName))
bindingContext.ModelState.AddModelError("FileName", "File Name: Field is required");
else if (fileName.Length > 50)
bindingContext.ModelState.AddModelError("FileNameLength", "FileName: Length should not be greater than 50 characters");
bool isPublished = !string.IsNullOrEmpty(isPublishedStr) ? Convert.ToBoolean(isPublishedStr.ToString()) : false;
//** TAGS
var tags = new List<PostTag>();
var tagIds = tagsStr.Split(',');
foreach (var tagId in tagIds)
{
tags.Add(repo.PostTag(int.Parse(tagId)));
}
if(tags.Count == 0)
bindingContext.ModelState.AddModelError("Tags", "Tags: The Post should have atleast one tag");
// retrieving the post type from repository.
int postTypeId = !string.IsNullOrEmpty(postTypeIdStr) ? int.Parse(postTypeIdStr) : 0;
var postType = repo.PostType(postTypeId);
if (postType == null)
bindingContext.ModelState.AddModelError("PostType", "Post Type is null");
Theme theme = null;
if (!string.IsNullOrEmpty(themeIdStr))
theme = repo.Theme(int.Parse(themeIdStr));
// serial no
if (oper.Equals("edit"))
{
if (string.IsNullOrEmpty(serialNoStr))
bindingContext.ModelState.AddModelError("SerialNo", "Serial No is empty");
else
serialNo = int.Parse(serialNoStr);
}
else
{
serialNo = repo.TotalPosts(false) + 1;
}
// check if commented date is not empty in edit.
if (string.IsNullOrEmpty(postedDateStr))
{
if (oper.Equals("edit"))
bindingContext.ModelState.AddModelError("PostedDate", "Posted Date is empty");
}
else
postedDate = Convert.ToDateTime(postedDateStr.ToString());
// CREATE NEW POST INSTANCE
return new Post
{
Id = id,
Heading = heading,
Description = description,
MetaTags = metaTags,
MetaDescription = metaDescription,
Tags = tags,
PostType = postType,
PostedDate = postedDate,
ModifiedDate = oper.Equals("edit") ? modifiedDate : null,
Published = isPublished,
FileName = fileName,
SerialNo = serialNo,
Theme = theme
};
}
#endregion
}
}
This line db.Entry(magazine).State = EntityState.Modified; only tells EF that magazine entity has changed. It says nothing about relations. If you call Attach all entities in object graph are attached in Unchanged state and you must handle each of them separately. What is even worse in case of many-to-many relation you must also handle relation itself (and changing state of relation in DbContext API is not possible).
I spent a lot of time with this problem and design in disconnected app. And there are three general approaches:
You will send additional information with your entities to find what has changed and what has been deleted (yes you need to track deleted items or relations as well). Then you will manually set state of every entity and relation in object graph.
You will just use data you have at the moment but instead of attaching them to the context you will load current magazine and every author you need and reconstruct those changes on those loaded entities.
You will not do this at all and instead use lightweight AJAX calls to add or remove every single author. I found this common for many complex UIs.

MVC3 RadioButtonFor value is not binded to the model

I have a MVC3 Razor form. It have a radiobutton list and some another text fields. When I press submit controller post action get the view model, which have all fields seted correctly, except RegionID.
Model:
namespace SSHS.Models.RecorderModels
{
public class CreateViewModel
{
...
public int RegionID { get; set; }
...
}
}
Controller:
namespace SSHS.Controllers
{
public class RecorderController : Controller
{
...
public ActionResult Create()
{
EntrantDBEntities db = new EntrantDBEntities();
List Regions = new List(db.Region);
List Schools = new List(db.School);
List Settlements = new List(db.settlement);
CreateViewModel newEntr = new CreateViewModel();
ViewBag.Regions = Regions;
ViewBag.Schools = Schools;
ViewBag.Settlements = Settlements;
return View(newEntr);
}
[HttpPost]
public ActionResult Create(CreateViewModel m)
{
EntrantDBEntities db = new EntrantDBEntities();
Entrant e = new Entrant()
{
FatherName = m.FatherName,
Lastname = m.LastName,
LocalAddress = m.LocalAddress,
Name = m.Name,
RegionID = m.RegionID,
PassportID = m.PassportID,
SchoolID = m.SchoolID,
SettlementID = m.SattlementID,
TaxID = m.TaxID,
};
db.Entrant.AddObject(e);
db.SaveChanges();
return RedirectToAction("Index");
}
}
View:
#model SSHS.Models.RecorderModels.CreateViewModel
#using SSHS.Models
#using (Html.BeginForm("Create", "Recorder", FormMethod.Post))
{
#foreach (Region item in ViewBag.Regions)
{
#Html.RadioButtonFor(m => m.RegionID, item.RegionID)
#Html.Label(item.RegionName) - #item.RegionID
}
...
...
}
The Create(CreateViewModel m) method gets data from all textboxes normaly, but RegionID always is 0.
How are you planning to fill radio button with int ? It have two states: checked and not. Could you tell us, what are you trying to do? Make radio group? Use bool for RadioButtonFor.
Added:
You need to write something like this: CheckboxList in MVC3.0 (in your example you will have radio buttons)

Resources