It is look like same question but mine little bit different.
Entity Framework 4 CTP 5 Self Referencing Many-to-Many
sample code;
public class Category
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Category> Parents { get; set; }
public virtual ICollection<Category> Children { get; set; }
}
I got right result when I define a field Parent as Category, instead of parents as List.
Category class well designed, but POCO? What should I do? Thanks in advance.
Your class works fine for me without any customizations. Even the [Key] attribute is not required.
Here's some code that exercises this model:
using (var context = new MyContext())
{
var parent1 = new Category { Name = "Parent 1" };
var parent2 = new Category { Name = "Parent 2" };
var child1 = new Category { Name = "Child 1" };
var child2 = new Category { Name = "Child 2" };
parent1.Children = new List<Category> { child1, child2 };
parent2.Children = new List<Category> { child1, child2 };
context.Categories.Add(parent1);
context.Categories.Add(parent2);
context.SaveChanges();
}
using (var context = new MyContext())
{
var categories = context.Categories.OrderByDescending(x => x.Children.Count)
.ToList();
foreach (var category in categories)
{
Console.Write(category.Name + ": ");
Console.WriteLine("Parents ({0}) Children ({1})",
string.Join(",", category.Parents.Select(x => x.Name).ToArray()),
string.Join(",", category.Children.Select(x => x.Name).ToArray()));
}
}
This will print:
Parent 1: Parents () Children (Child 1,Child 2)
Parent 2: Parents () Children (Child 1,Child 2)
Child 1: Parents (Parent 1,Parent 2) Children ()
Child 2: Parents (Parent 1,Parent 2) Children ()
Related
I'm making a strongly typed update/create view for "Medical Supplies" in which users can select multiple options ("Kits") from a dropdown list that received a List<SelectListItem>. The list is a <select multiple="multiple">. It was originally working perfectly, but I must have accidentally changed something.
Now the dropdown does not display SelectListItems passed to it as selected = true as selected (as verified by VS debugger), so I can select new items but not deselect previously selected ones. I need this to compare the list of IDs from the new selection to the old one in order to determine what must be removed from the Db.
This is my view model:
public class MedicalSupplyViewModel
{
public MedicalSupplyViewModel()
{
Supply = new MedicalSupply();
KitList = new List<SelectListItem>();
KitIds = new List<int>();
}
public MedicalSupply Supply { get; set; }
public List<SelectListItem> KitList { get; set; }
public string StringKits { get; set; }
public List<int> KitIds { get; set; }
public void KitStringSet()
{
IEnumerable<string> KitNames = Supply.KitSupplies.Select(ks => ks.Kit.Name);
StringKits = Supply.KitSupplies.Count() == 0 ? "N/A" : string.Join(", " , KitNames);
}
}
This is the relevant cshtml in my view:
<select multiple="multiple" class="form-control" id="kit_select" asp-for="KitIds" asp-items="Model.KitList"></select>
This is the part of the controller method for this page that creates the SelectListItems:
DetailsModel.KitList = _db.Kits.ToList().ConvertAll(k =>
{
return new SelectListItem()
{
Value = k.Id.ToString(),
Text = k.Name,
Selected = SelectedKits.Contains(k)
};
});
Even setting the item to selected = true will not display them as such. I've set breakpoint everywhere, including in the view, and I cannot find a discrepancy between the selected property and what it should be anywhere except for the rendered html. I've also used different browsers and spent hours searching the internet and this website.
What could be the cause of this issue?
You should set the selected items' value to the KitIds. Below is my test example:
Model:
public class MedicalSupplyViewModel
{
public MedicalSupplyViewModel()
{
KitList = new List<SelectListItem>();
KitIds = new List<int>();
}
public List<SelectListItem> KitList { get; set; }
public string StringKits { get; set; }
public List<int> KitIds { get; set; }
}
public class Kit
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller:
public IActionResult Index()
{
List<Kit> kits = new List<Kit>
{
new Kit{ Id = 1, Name = "AA"},
new Kit{ Id = 2, Name = "BB"},
new Kit{ Id = 3, Name = "CC"},
};
List<Kit> SelectedKits = new List<Kit>
{
new Kit{ Id = 1, Name = "AA"},
new Kit{ Id = 2, Name = "BB"}
};
var DetailsModel = new MedicalSupplyViewModel();
DetailsModel.KitIds = SelectedKits.Select(x => x.Id).ToList();
DetailsModel.KitList = kits.ToList().ConvertAll(k =>
{
return new SelectListItem()
{
Value = k.Id.ToString(),
Text = k.Name
};
});
return View(DetailsModel);
}
View:
<select multiple="multiple" class="form-control" id="kit_select" asp-for="KitIds" asp-items="Model.KitList"></select>
Result:
I am in a big trouble. I read 4 stackoverflow question and one blogpost. I have tried 5 different approach to view the selected items in a multiple selectlist.
I have no success.
The multiple selectlist is generated, but it does not select the items. I have no more idea.
Model:
public class EditableModel
{
public IList<Company> SelectedCompanies { get; set; }
public IList<SelectListItem> SelectListCompanies { get; set; }
}
Controller:
public ActionResult Edit(int id)
{
var service = _serviceDAL.GetEditableModel(id);
if (service!= null)
{
service.SelectListCompanies = GetSelectListCompanies(service.SelectedCompanies);
return View(service);
}
}
private IList<SelectListItem> GetSelectListCompanies(IList<Company> selectedCompanies)
{
List<SelectListItem> items = new List<SelectListItem>();
foreach (Companycompany in _companyService.GetCompanies())
{
items.Add(new SelectListItem
{
Value = company.CompanyId.ToString(),
Text = company.Name,
Selected = selectedCompanies.Any(x => x.CompanyId == company.CompanyId)
});
}
return items;
}
View
#Html.ListBox("SelectedCompanies", Model.SelectListCompanies, Model.SelectedCompanies.Select(x => x.CompanyId.ToString()) )
And nothing. The items in the select list is not selected...
I have tried this Multiselect, the same result, or this one as the current solution.
You cannot bind a <select multiple> to a collection of complex objects. It binds to, and posts back an array of simple values (the values of the selected options).
Your SelectedCompanies property needs to be IEnumerable<int> (assuming the CompanyId of Company is also int). Note also the Selected property of SelectListItem is ignored when binding to a property.
Your also using the same collection for the selected Companies and the list of all Companies which makes no sense. Your SelectListCompanies should be generated from your table of Company.
Model
public class MyViewModel
{
public IEnumerable<int> SelectedCompanies { get; set; }
public IEnumerable<SelectListItem> SelectListCompanies { get; set; }
}
Base on your current code for EditableModel, your code should be
public ActionResult Edit(int id)
{
var service = _serviceDAL.GetEditableModel(id);
....
MyViewModel model = new MyViewModel
{
SelectedCompanies = service.SelectedCompanies.Select(x => x.CompanyId),
SelectListCompanies = GetSelectListCompanies()
};
return View(model);
private IEnumerable<SelectListItem> GetSelectListCompanies()
{
var all companies = ... // call method to get all Companies
return companies.Select(x => new SelectListItem
{
Value = x.CompanyId.ToString(),
Text = x.Name
});
}
However, it look like you should be modifying your EditableModel and the GetEditableModel() code to return the correct data in the first place.
Since i have never used a drop down list in MVC before, I am having problems creating one.
I have looked it up but i am not understanding. I want to create a basic drop down list for "Gender" in MVC3.
So far i have been able to create this.
Class:
public Dictionary<int, string> Gender {get;set; }
public StudentInformation()
{
Gender = new Dictionary<int, string>()
{
{ 0, "Male"},
{ 1, "Female"},
};
}
View:
#Html.DropDownListFor(model => model.Gender.Keys,
new SelectList(
Model.Gender,
"Key",
"Value"))
But it throws an exception "Object reference not set to an instance of the object".
Here are a bunch of different ways.
http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc
Here is my solution for this,
public class Blog {
private readonly IList<Post> _list = new List<Post> {
new Post(1, "How to 1"),
new Post(2, "How to 2"),
new Post(3, "How to 3"),
new Post(4, "How to 4"),
new Post(5, "How to 5")
};
public SelectList Posts {
get {
return new SelectList(_list, "PostId", "Title");
}
}
public int? SelectedPostId { get; set; }
}
public class Post {
public Post(int postId, string title) {
PostId = postId;
Title = title;
}
public int PostId { get; set; }
public string Title { get; set; }
}
//The View:
#Html.DropDownFor(o => o.SelectedPostId, Model.Posts)
Here is the link for more of explanations:
Reference
Try This....
Controller
var value = new SelectList(new[]
{
new {ID="1",Name="ISO 9001"},
new{ID="2",Name="BIS Hallmark"},
new{ID="3",Name="ISI"},
});
ViewData["values "] = value
VIEW
#Html.DropDownList("Cert", (SelectList)ViewData["Certification"], "--Select--", new { #class="dropdownlist" ,id = "Cert" })
I m new in MVC framework. my query is i have to receive data from database sql
database. and display in .cshtml
.plz help....
public ActionResult Index()
{
var model = (from p in am.AMS_Page_Accesses
where p.Role_id == "m"
select new {
p.Name,
p.Id,
p.Link
}).ToList();
var abc= new linkname
{
}
return View(abc);
}
Model
public class linktab
{
public string id { get; set; }
public string Name { get; set; }
public string link { get; set; }
}
public class linkname
{
public List<linktab> menu { get; set; }
}
in .cshtml
#foreach (var a in Model)
{
<div>a.Name</div>
<div>a.Id</div>
<div>a.Link</div>
}
You did not show what exactly is your view's model, according to the error you got it seems you did not specify it at all (using the #model directive).
Try this
public ActionResult Index()
{
var model = (from p in am.AMS_Page_Accesses
where p.Role_id == "m"
select new linktab
{
Id = p.Id,
Link = p.Link,
Name = p.Name
}).ToList();
var abc = new linkname
{
menu = model
}
return View(abc);
}
In your view:
#model linkname
#foreach (var a in Model.menu)
{
<div>a.Name</div>
<div>a.Id</div>
<div>a.Link</div>
}
You're sending an Empty collection change you action like this,
I'm assuming that your view it's strongly typed to the List of linktab
public ActionResult Index()
{
var model = (from p in am.AMS_Page_Accesses
where p.Role_id == "m"
select new linktab{
Name = p.Name,
id = p.Id,
link = p.Link
}).ToList();
return View(model);
}
If it's not the case and your model it's strongly type to the class linkname you should do your action like this
public ActionResult Index()
{
var model = (from p in am.AMS_Page_Accesses
where p.Role_id == "m"
select new linktab{
Name = p.Name,
id = p.Id,
link = p.Link
}).ToList();
linkname abc= new linkname
{
menu = model
}
return View(abc);
}
And you may change the code in your view something like this
#foreach (var a in Model.menu)
{
<div>a.Name</div>
<div>a.Id</div>
<div>a.Link</div>
}
i've a view. in the view i've months field(nvarchar type in database) :
#Html.DropDownListFor(model => model.rent_month,
(IEnumerable<SelectListItem>)ViewBag.months)
i've a method in a model class (PostManager) to generate months list like:
public IEnumerable<SelectListItem> GetMyMonthList()
{
return CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
.Select(m => new SelectListItem() { Text = m, Value = m });
}
i get months in get action by :
public ActionResult Create()
{
PostModel p = new PostModel();
ViewBag.months = pm.GetMyMonthList();
return View(p);
}
in my Model my month attributes:
[Required(ErrorMessage = "You Must Select a Month.")]
[Display(Name = "Select Rent Month")]
public string rent_month { get; set; }
in the post action:
public ActionResult Create(PostModel p)
{
if (ModelState.IsValid)
{
post post = new Models.DB.post();
post.rent_month = p.rent_month;
db.posts.AddObject(post);
db.SaveChanges();
}
}
it generates month in the dropdownlist correctly.But after submit the form it gives error:
The ViewData item that has the key 'rent_month' is of type 'System.String' but must be of type 'IEnumerable'
now what is the solution for this error... thanks in advance...
I believe this is happening because in your post action you are not populating the ViewBag again. Make sure you set ViewBag.months = pm.GetMyMonthList(); in your controller POST action similar to what you have done in GET action.
Better solution would be to have a IEnumerable<SelectListItem> MonthList property as part of the PostModel. Instead of loading the months from ViewBag you can access it directly by the MonthList property
In the PostModel
public IEnumerable<SelectListItem> MonthList
{
get
{
return pm
.GetMonthList()
.Select(a => new SelectListItem
{
Value = a.Id,
Text = a.MonthText
})
.ToList();
}
}
Then in the view
#Html.DropDownListFor(model => model.rent_month, Model.MonthList)
After EDIT to the question
Your PostModel class should be like this. I have moved your GetMyMonthList() implementation out of the PostManager class.
public class PostModel
{
[Required(ErrorMessage = "You Must Select a Month.")]
[Display(Name = "Select Rent Month")]
public string rent_month { get; set; }
public IEnumerable<SelectListItem> MonthList
{
get
{
return CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
.Select(m => new SelectListItem() { Text = m, Value = m });
}
}
}
public class PostModel
{
[Required(ErrorMessage = "You Must Select a Month.")]
[Display(Name = "Select Rent Month")]
public string rent_month { get; set; }
public IEnumerable<SelectListItem> MonthList
{
get
{
return CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
.Select(m => new SelectListItem() { Text = m, Value = m });
}
}
}