#Html.LisboxFor Model Binding for multiple items - asp.net-mvc-4

My Class is
public partial class Team
{
public int TeamId { get; set; }
public string TeamName { get; set; }
public string TeamDescription { get; set; }
public virtual IList<Trials> Trials { get; set; }
}
Trials is anothetr calss
public partial class Trials
{
public int TrialID { get; set; }
public string Name { get; set; }
public int TrialTyp_RefID { get; set; }
public bool isChk { get; set; }
public virtual ICollection<Team> Team { get; set; }
}
in my view I amn trying to bind the ListBoxFor with Trials inseide the team
#model Trials.Classes.Team
<td colspan="2">
#Html.ListBoxFor(model=> model.Trials,
new SelectList(ViewBag.trials,"TrialID", "Name"),
new { #class = "chosen-select", data_placeholder = "Select Trials...", style = "width:500px;", tabindex = "4" }
)
</td>
I cant get any value for Trials calss in the controller ..It shows null but I select multi values from listbox

A multiple select only posts back an array of primitive values. It does not post back a collection of complex objects.
You need a view model with a property to bind the selected Trials
public class TeamVM
{
public int TeamId { get; set; }
....
public int[] SelectedTrials { get; set; }
public SelectList Trials { get; set; } // Assign this in your controller rather than using ViewBag
}
then in you view
#Html.ListBoxFor(m => m.SelectedTrials, Model.Trials)
When you post back, Team.SelectedTrials will contain and array of the selected TrialID values.

I changed the Team class as
public partial class Team
{
public int TeamId { get; set; }
public string TeamName { get; set; }
public string TeamDescription { get; set; }
public virtual IList<Trials> Trials { get; set;
public int[] AuthorisedTrials { get; set; }
}
and in View
#model Trials.Classes.Team
<td colspan="2">
#Html.ListBoxFor(model=> model.AuthorisedTrials ,
new SelectList(ViewBag.trials,"TrialID", "Name"),
new { #class = "chosen-select", data_placeholder = "Select Trials...", style = "width:500px;", tabindex = "4" }
)
</td>
and in my controller I was able to get the Vlaues for Selected Trials

Related

How to establish one-to-many relationship for a code-first approach?

I'm trying to build a recipe app for my spouse. I'm trying to set it up so she can add new recipes to the database as the app grows.
When adding new recipe, she will have three drop-down to pick from to construct her new recipe ingredients. First one will contain a list of ingredients that she can choose from, the second one a list of measuring units and the third one a list of quantities.
Here is what I got so far. Am I heading in the right direction or am I off? I'm using Entity Framework with a code-first approach:
public class Recipes
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
}
public class Units model
{
[Key]
public int Id { get; set; }
public string UnitName { get; set; }
}
public class UnitQty
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class IngredientsModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class RecipeIngredients
{
public int Id { get; set; }
public int RecipesId { get; set; }
[ForeignKey("RecipesId")]
public Recipes Recipes { get; set; }
public int IngredientsModelId { get; set; }
[ForeignKey("IngredientsModelId")]
public IngredientsModel IngredientsModel { get; set; }
public int UnitQtyId { get; set; }
[ForeignKey("UnitQtyId")]
public UnitQty UnitQty { get; set; }
public int UnitsModelId { get; set; }
[ForeignKey("UnitsModelId")]
public UnitsModel UnitsModel { get; set; }
}
After creating the table, controller and the views, this is what I get in the recipe ingredients index view.
Any suggestion will be more than welcome please and thank you
RecipeIngredient class's view
First of all. You are over engineering your domain model. On relational databases Join is bottleneck you should prevent from joins if it doesn't helps you.
public class Recipt
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public ICollection<RecipeIngredient> Ingredients { get; set; }
}
public class IngredientModel
{
public int Id { get; set; }
public string Name { get; set; }
public IngredientUnit UnitType { get; set; } // Unit model is best to be added here. if it doesn't change in a single IngredientModel.
}
public class RecipeIngredient
{
public int Id { get; set; }
public int UnitQuantiy { get; set; } // No need to more classes.
public IngredientModel Model { get; set; }
public Recipt Recipt { get; set; }
}
public Enum IngredientUnitType // Same Unit Model but less database relation as its small finite collection.
{
Killogram,
Count,
....
}
and according to the Microsoft documents its best to use fluentApi configuration for the relations.
Override this method in your Context:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Recipt>.HasMany(P => P.Ingredients).WithOne(P => P.Recipt);
builder.Entity<RecipeIngredient>.HasOne(P => P.Model);
// There is no need to explicit foreign key definition. but you can explicitly define your foreign keys.
}
And for the last part. in Views you can use extra models called ViewModels.
As above domain turned to a minimal domain you just need to pass a list of IngredientModels to your view to complete your View.

create CheckboxFor from List in View Model

My View Model Class is
public class StudentQuestions
{
public int StudentId{ get; set; }
public int FormId { get; set; }
public virtual ICollection<Questions> Question { get; set; }
}
and question class is
public partial class Questions
{
public int questionID { get; set; }
public string field_name { get; set; }
public string question { get; set; }
public int qutyp_refID {get,set}
public string description { get; set; }
public int ord { get; set; }
public bool IsEnabled { get; set;}
public virtual ICollection<Answers> Answers { get; set; }
}
in my view
#model Test.ViewModels.StudentQuestions
<table>
<tr><td>#Model.FormId</td><td>#Model.StudentId</td></tr>
#foreach(var q in Model.Question)
{
<tr>
<td> #Html.CheckBoxForFor(i=> i.Question.question)</td>
</tr>
}
</table>
I cant access i.Question.question but I can access in CheckBox, TextBox like following and I want to change Textbox to TextBoxFor and CheckBox to CheckBoxFor and TextBox to TextBoxFor
#foreach(var q in Model.Question)
{
<tr>
#if (#q.qutyp_refID == 4)
{
<td>#Html.CheckBox(q.questionID.ToString())
</td>
}
else if (#q.qutyp_refID <= 2)
{
<td>#Html.TextBox("txtDateQuestions", DateTime.Today.ToString("dd/MM/yyyy"), new { style = "width: 120px" }) </td>
}
else
{
<td>#Html.TextBox(q.questionID.ToString(), null)</td>
}
</tr>
}
Thanks in Advance.........
Try like this,
#Html.CheckBoxFor(i => m.questionID, new { id = #m.questionID, #checked = "checked", Name = "CheckBox" })<span>m.description</span>
Example
Model
public class AssignProject
{
public Guid Id { get; set; }
public string EmployeesName { get; set; }
public Guid? EmployeeId { get; set; }
public Guid? ProjectId { get; set; }
public string AssignEmployeeId { get; set; }
public bool IsChecked { get; set; }
}
View
#foreach (var item in Model)
{
#Html.CheckBoxFor(m => item.IsChecked, new { value = item.EmployeeId, id = "chk_" + #item.EmployeeId, #checked = "checked", Name = "CheckBox" })
}

System.Collections.Generic.IEnumerable<MyBlogSite.Models.BlogPost>' does not contain a definition for 'Categories'

Here is my BlogPost Model class:
public class BlogPost
{
public int Id { get; set; }
public string Title { get; set; }
[AllowHtml]
public string ShortDescription { get; set; }
[AllowHtml]
public string PostBody { get; set; }
public string Meta { get; set; }
public string UrlSlug { get; set; }
public DateTime PostedOn { get; set; }
public DateTime? Modified { get; set; }
public virtual ICollection<BlogPostCategory> Categories { get; set; }
public virtual ICollection<BlogPostTag> Tags { get; set; }
}
Here is my BlogPostCategory Model class:
public class BlogPostCategory
{
public int Id { get; set; }
public string Name { get; set; }
public string UrlSlug { get; set; }
public string Description { get; set; }
// Decared virtual because the data must be returned from another table.
public virtual ICollection<BlogPost> BlogPosts { get; set; }
}
Each class belongs to a separate Controller/View.
Finally, here is the top port of the Index View for Blog:
#model IEnumerable<MyBlogSite.Models.BlogPost>
#{
ViewBag.Title = "Index";
}
#Html.RenderPartial("~/Views/Category/_Categories.cshtml", Model.Categories );
<p>
#Html.ActionLink("New Blog Post", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
....
In the View where Model.Categories is being passed in is where I am getting the exception from the title of this post. It seems to me that I have defined Categories within the BlogPost Model. What am I doing wrong?
The Model on your Razor page is an IEnumerable<MyBlogSite.Models.BlogPost>. It seems you're trying to display the information about each of the items in your collection. If so, then you can loop through them or create a display/editor template and use #Html.DisplayFor(x => x) or #Html.EditorFor(x => x), respectively.
#foreach(var post in Model) {
<p>Do stuff here with the local "post" variable.</p>
}
Here's a link to Scott Gu's blog talking about the #model directive in Razor views.

Accessing data in a ViewModel

I have the following entity framework code snippet which has a "Groups" table and a child "ApplicationsGroupsLK" table that contains an ApplicationID field that I need.
IEnumerable<Groups> Groups = DbContext.Groups.Include("ApplicationsGroupsLK").Where(p => p.GroupNumber > 0);
The child data comes back obviously in a collection.
I basically need to display the parent data along with the child ApplicationID field (many Applications to 1 Group).
In my MVC View, what should my ViewModel look like that would contain the parent and child data coming back that I need in order that I can properly bind it to a grid?
Second post:
Further, the following model was generated from Entity Framework:
public partial class Project
{
public Project()
{
this.TimeTrackings = new HashSet<TimeTracking>();
}
[DataMember]
public short ProjectID { get; set; }
[DataMember]
public short CustomerID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public short CategoryID { get; set; }
[DataMember]
public short PriorityID { get; set; }
[DataMember]
public short StatusID { get; set; }
[DataMember]
public Nullable<decimal> Quote { get; set; }
[DataMember]
public string Notes { get; set; }
[DataMember]
public System.DateTime CreatedDate { get; set; }
[DataMember]
public Nullable<System.DateTime> UpdatedDate { get; set; }
[DataMember]
public virtual Category Category { get; set; }
[DataMember]
public virtual Customer Customer { get; set; }
[DataMember]
public virtual Priority Priority { get; set; }
[DataMember]
public virtual Status Status { get; set; }
[DataMember]
public virtual ICollection<TimeTracking> TimeTrackings { get; set; }
}
You can see that TimeTrackings is the child table of Project. You can also see that CategoryID, CustomerID, PriorityID, and StatusID are foreign keys that the parent table has. In this case, I'm only interested in the CategoryID FK.
I haven't done this yet (not at my machine at home), but when I get the data into this model, what would actually be contained in the public virtual Category Category field? Since it's not a collection, what data is returned in this field after the query executes.
Third post:
Telerik asp.net for mvc syntax for DB call:
IEnumerable<Groups> GroupList = db.GetGroups();
return View(new GridModel<Groups>
{
Data = GroupList
});
Fourth post:
Trey, below is the code I modified for my purposes and was hoping you can check it over before I implement it. I think I undersand it and seems great...
public partial class Project
{
public Project()
{
this.TimeTrackings = new HashSet<TimeTracking>();
}
[DataMember]
public short ProjectID { get; set; }
[DataMember]
public short CustomerID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public short CategoryID { get; set; }
[DataMember]
public short PriorityID { get; set; }
[DataMember]
public short StatusID { get; set; }
[DataMember]
public Nullable<decimal> Quote { get; set; }
[DataMember]
public string Notes { get; set; }
[DataMember]
public System.DateTime CreatedDate { get; set; }
[DataMember]
public Nullable<System.DateTime> UpdatedDate { get; set; }
[DataMember]
public short ApplicationID { get; set; }
[DataMember]
public string ApplicationName { get; set; }
[DataMember]
public virtual Category Category { get; set; }
[DataMember]
public virtual Customer Customer { get; set; }
[DataMember]
public virtual Priority Priority { get; set; }
[DataMember]
public virtual Status Status { get; set; }
[DataMember]
public virtual ICollection<TimeTracking> TimeTrackings { get; set; }
public ProjectModel(Project project)
{
ProjectID = project.ProjectID;
CustomerID = project.CustomerID;
Name = project.Name;
Description = project.Description;
CategoryID = project.CategoryID;
PriorityID = project.PriorityID;
StatusID = project.StatusID;
Quote = project.Quote;
Notes = project.Notes;
CreatedDate = project.CreatedDate;
UpdatedDate = project.UpdatedDate;
ApplicationID = project.ApplicationsGroupsLK.ApplicationID;
ApplicationName = project.ApplicationsGroupsLK.ApplicationName;
}
// Neat Linq trick to convert database query results directly to Model
public static IList<ProjectModel> FlattenToThis(IList<Project> projects)
{
return projects.Select(project => new ProjectModel(project)).ToList();
}
}
Fifth post:
using (wmswebEntities DbContext = new wmswebEntities())
{
DbContext.Configuration.ProxyCreationEnabled = false;
DbContext.Database.Connection.Open();
IEnumerable<Projects> projects = DbContext.Projects.Where(p => p.GroupNumber > 0);
IList<ProjectModel> results = Project.FlattenToThis(projects);
return results
}
Sixth post
namespace CMSEFModel
{
using System;
using System.Collections.Generic;
public partial class GroupModel
{
public GroupModel()
{
this.ApplicationsGroupsLKs = new HashSet<ApplicationsGroupsLK>();
this.GroupApplicationConfigurationsLKs = new HashSet<GroupApplicationConfigurationsLK>();
this.UsersGroupsLKs = new HashSet<UsersGroupsLK>();
}
public int GroupNumber { get; set; }
public string GroupName { get; set; }
public int GroupRank { get; set; }
public bool ActiveFlag { get; set; }
public System.DateTime DateAdded { get; set; }
public string AddedBy { get; set; }
public System.DateTime LastUpdated { get; set; }
public string LastUpdatedBy { get; set; }
// Application - Lazy Loading population
public int ApplicationID { get; set; }
// UsersGroupsLK - Lazy Loading population
public int UserNumber { get; set; }
public string UserID { get; set; }
public virtual ICollection<ApplicationsGroupsLK> ApplicationsGroupsLKs { get; set; }
public virtual ICollection<GroupApplicationConfigurationsLK> GroupApplicationConfigurationsLKs { get; set; }
public virtual ICollection<UsersGroupsLK> UsersGroupsLKs { get; set; }
public GroupModel()
{}
public GroupModel(GroupModel group)
{
GroupNumber = group.GroupNumber;
GroupName = group.GroupName;
ActiveFlag = group.ActiveFlag;
DateAdded = group.DateAdded;
AddedBy = group.AddedBy;
LastUpdated = group.LastUpdated;
LastUpdatedBy = group.LastUpdatedBy;
UserNumber = group.UsersGroupsLKs.
}
// Neat Linq trick to convert database query results directly to Model
public static IList<GroupModel> FlattenToThis(IList<GroupModel> groups)
{
return groups.Select(group => new GroupModel(group)).ToList();
}
}
}
Seventh Post - this is the model I am having trouble with about the errors I previously posted. Trey, if you could help, I WOULD REALLY APPRECIATE IT.... I'm "dead in the water" unless I can get this part working.
namespace CMSEFModel
{
using System;
using System.Collections.Generic;
public partial class Group
{
public Group()
{
this.ApplicationsGroupsLKs = new HashSet<ApplicationsGroupsLK>();
this.GroupApplicationConfigurationsLKs = new HashSet<GroupApplicationConfigurationsLK>();
this.UsersGroupsLKs = new HashSet<UsersGroupsLK>();
}
public int GroupNumber { get; set; }
public string GroupName { get; set; }
public int GroupRank { get; set; }
public bool ActiveFlag { get; set; }
public System.DateTime DateAdded { get; set; }
public string AddedBy { get; set; }
public System.DateTime LastUpdated { get; set; }
public string LastUpdatedBy { get; set; }
// Application - Lazy Loading population
public int ApplicationID { get; set; }
// UsersGroupsLK - Lazy Loading population
public int UserNumber { get; set; }
public string UserID { get; set; }
public virtual ICollection<ApplicationsGroupsLK> ApplicationsGroupsLKs { get; set; }
public virtual ICollection<GroupApplicationConfigurationsLK> GroupApplicationConfigurationsLKs { get; set; }
public virtual ICollection<UsersGroupsLK> UsersGroupsLKs { get; set; }
public GroupModel(Group group)
{
GroupNumber = group.GroupNumber;
GroupName = group.GroupName;
ActiveFlag = group.ActiveFlag;
DateAdded = group.DateAdded;
AddedBy = group.AddedBy;
LastUpdated = group.LastUpdated;
LastUpdatedBy = group.LastUpdatedBy;
UserNumber = group.UsersGroupsLKs.
}
// Neat Linq trick to convert database query results directly to Model
public static IList<GroupModel> FlattenToThis(IList<Group> groups)
{
return groups.Select(group => new GroupModel(group)).ToList();
}
}
}
Eight post:
using (wmswebEntities DbContext = new wmswebEntities())
{
DbContext.Configuration.ProxyCreationEnabled = false;
DbContext.Configuration.LazyLoadingEnabled = true;
DbContext.Database.Connection.Open();
List<Groups> myGroups = new List<Groups>();
var myGroups = from p in DbContext.Groups
where p.ActiveFlag = true
select new
{
p.Groups.ApplicationName,
p.Groups.GroupName,
p.Groups.GroupRank,
p.Groups.ActiveFlag,
p.Groups.DateAdded,
p.Groups.AddedBy,
p.Groups.LastUpdated,
p.Groups.LastUpdatedBy,
p.Groups.ApplicationsGroupsLK.ApplicationID,
p.Groups.UsersGroupsLK.UserNumber
};
return myGroups;
}
This will take a slight tweak in thinking. The Grid will only accept a flat model. This type of question is asked often, here is a starter answer: Kendo UI Grid - How to Bind to Child Properties
If that does not help, post more of your code here and I can work through it with you.

How does one get row data from a Silverlight DataGrid?

In Silverlight, how does one get row data from a DataGrid that is full of data?
I have gotten this far (in a method that receives a button click on a row(:
DataGridRow item = (DataGridRow)dg.SelectedItem;
Now, how do I get the individual components of the item that I guess is the selected row?
Help me out here. How do you bind an observablecollection to the grid?
How do you use the cast system when you cast to the object?
When I read the data into the grid, I used this class:
public class Data
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public bool Available { get; set; }
public int index_1 { get; set; }
public int index_2 { get; set; }
public int index_3 { get; set; }
public int index_4 { get; set; }
public int index_5 { get; set; }
public int index_6 { get; set; }
public int index_7 { get; set; }
public int index_8 { get; set; }
public int index_9 { get; set; }
public int index_10 { get; set; }
public int index_11 { get; set; }
public int index_12 { get; set; }
public int index_13 { get; set; }
public int index_14 { get; set; }
public int index_15 { get; set; }
}
So how so I cast when I read back out
This does not work:
Data _mydata = new Data();
YValue = (_mydata.index_1)dg.SelectedItem;
This does not work:
YValue = (index_1)dg.SelectedItem;
This does not work:
YValue = (Data().index_1)dg.SelectedItem;
DataGridRow item = (DataGridRow)dg.SelectedItem;
int index1 = ((Data)item).index_1;
That will give you the value of the first index.
If you have bound a ObservableCollection<Foo> to your grid, your selected item can just be cast into your object - (Foo)dg.SelectedItem
EDIT-- UPDATE TO ANSWER UPDATED QUESTION
The simple answer is, if you are not using MVVM (which I assume by your post your not), in the code behind create a collection (preferably ObservableCollection) of Data and set the grids itemsource property to your collection
public ObservableCollection<Data> MyCollection{get;set;}
void SetGridItemsSource()
{
// populate your collection here, then use the below line to associate it with your
// grids itemssource
MyGrid.ItemsSource = MyCollection;
}
public void GetSelectedItem()
{
//Simply cast the selected item to your type
Data selectedItem = (Data)MyGrid.SelectedItem;
}