Self referring hierarchical data binding - asp.net-mvc-3

I'm using Extensions for ASP.NET MVC Q3 2011(open source version) with Razor engine and Asp.net MVC3 architecture.
I want to bind a grid to a entity in my database which has self referring structure (like a tree). Therefore, I can not define it like examples with fixed levels, because I do not know how many levels this grid has. So, I want to bind my grid dynamically to a model.
public class Category : Entity
{
public virtual int Id {private set; get; }
public virtual string Title { set; get; }
public virtual string Description { set; get; }
public virtual string ParentsPath { set; get; }
public virtual IList<Category> Children { get; private set; }
public virtual Category Parent { get; set; }
}
I'm also using Fluent NHibernate and because of that I store children and parent in my entity.
Is there a way to do this? I couldn't find anything in documentations.
Am I missing something? because in Ajax and Winform components, it has been implemented.
Thanks.

You cannot do it automatically, You need a foreach iteration and generating the items and then add them to the tree manually.
I did it for PanelBar when I needed to show a hierarchicy.
Here is an example :
#(Html.Telerik().PanelBar()
.Name("Details")
.ExpandMode(PanelBarExpandMode.Multiple)
.Items(items =>
{
var parent = Model.ParentWorkItem;
List<WorkItem> lst = new List<WorkItem>();
while (parent != null)
{
lst.Add(parent);
parent = parent.ParentWorkItem;
};
for (int i = lst.Count-1; i >=0;i-- )
{
parent = lst[i];
items.Add()
.Expanded(false)
.Text("...")
.LoadContentFrom(...);
}
items.Add()
.Expanded(true)
.Text(...)
.Content(....);
})
)
Hope to be helpful.

Related

How to update hierarchical ViewModel?

I am stuck with this problem.
I have a model AssessmentModel defined like this:
public class AssessmentModel
{
public Respondent Respondent { get; set; }
public List<CompetencyModel> Competencies { get; set; }
}
public class CompetencyModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<ResultModel> Results { get; set; }
}
public class ResultModel
{
public int Id { get; set; }
public int Score { get; set; }
}
All I need is to set value to the Score property of ResultModel.
Score is the only editable property here.
And I have just 1 View only, this view has a #model List, it displays a list of CompetencyModel items with Edit button for each one.
When I click the Edit button, the Id of CompetencyModel is passed to the same View, and the View draws an Edit form for ResultModel items that belong to the selected CompetencyModel.
However the form for ResultModel items exists on the same View, and the model of the View is still #model List.
How can I get to the Score property by using bindable Html.EditorFor(m=>m.Score) helper for each ResultModel item?
The View is defined like this:
#model List<CompetencyModel>
#foreach(var comp in Model)
{
<p>#comp.Name</p>
Edit
}
In the controller I set ViewBag.CurrentId = comp.Id, and at the bottom of the View:
if(ViewBag.CurrentId != null) //draw a form for ResultModel items
{
// What should I do now?
// how cant I use Html.EditorFor(m=>...) if the Model is still List<CompetencyModel>
}
I need to get to a single ResultModel entity to set a value to a Score property.
Thank you.
You should be able to get this done using Linq. Consider having the following code segment in the your last if statement
var result = Model.Results.FirstOrDefault(r => r.Id == ViewBag.CurrentId);
I dont have a IDE with me, so watchout for syntext errors

implementing dropdownlist in asp.net mvc 3

I am teaching myself asp .net mvc3. I have researched a lot but the more I read the more confused I become. I want to create a page where users can register their property for sale or rent.
I have created a database which looks like this:
public class Property
{
public int PropertyId { get; set; }
public int PropertyType { get; set; }
ยทยทยท
public int Furnished { get; set; }
...
}
Now, I want dropdownlistfor = PropertyType and Furnished.
Property type would be
1 Flat
2 House
3 Detached House
...
Furnished would be:
1 Furnished
2 UnFurnished
3 PartFurnished
...
Now, I am really not sure where to keep this information in my code. Should I have 2 tables in my database which store this lookup? Or should I have 1 table which has all lookups? Or should I just keep this information in the model?
How will the model bind to PropertyType and Furnished in the Property entity?
Thanks!
By storing property types and furnished types in the database, you could enforce data integrity with a foreign key, rather than just storing an integer id, so I would definitely recommend this.
It also means it is future proofed for if you want to add new types. I know the values don't change often/will never change but if you wanted to add bungalow/maisonette in the future you don't have to rebuild and deploy your project, you can simply add a new row in the database.
In terms of how this would work, I'd recommend using a ViewModel that gets passed to the view, rather than passing the database model directly. That way you separate your database model from the view, and the view only sees what it needs to. It also means your drop down lists etc are strongly typed and are directly in your view model rather than just thrown into the ViewBag. Your view model could look like:
public class PropertyViewModel
{
public int PropertyId { get; set; }
public int PropertyType { get; set; }
public IEnumerable<SelectListItem> PropertyTypes { get; set; }
public int Furnished { get; set; }
public IEnumerable<SelectListItem> FurnishedTypes { get; set; }
}
So then your controller action would look like:
public class PropertiesController : Controller
{
[HttpGet]
public ViewResult Edit(int id)
{
Property property = db.Properties.Single(p => p.Id == id);
PropertyViewModel viewModel = new PropertyViewModel
{
PropertyId = property.Id,
PropertyType = property.PropertyType,
PropertyTypes = from p in db.PropertyTypes
orderby p.TypeName
select new SelectListItem
{
Text = p.TypeName,
Value = g.PropertyTypeId.ToString()
}
Furnished = property.Furnished,
FurnishedTypes = from p in db.FurnishedTypes
orderby p.TypeName
select new SelectListItem
{
Text = p.TypeName,
Value = g.FurnishedTypeId.ToString()
}
};
return View();
}
[HttpGet]
public ViewResult Edit(int id, PropertyViewModel propertyViewModel)
{
if(ModelState.IsValid)
{
// TODO: Store stuff in the database here
}
// TODO: Repopulate the view model drop lists here e.g.:
propertyViewModel.FurnishedTypes = from p in db.FurnishedTypes
orderby p.TypeName
select new SelectListItem
{
Text = p.TypeName,
Value = g.FurnishedTypeId.ToString()
};
return View(propertyViewModel);
}
}
And your view would have things like:
#Html.LabelFor(m => m.PropertyType)
#Html.DropDownListFor(m => m.PropertyType, Model.PropertyTypes)
I usually handle this sort of situation by using an enumeration in code:
public enum PropertyType {
Flat = 1,
House = 2,
Detached House = 3
}
Then in your view:
<select>
#foreach(var val in Enum.GetNames(typeof(PropertyType)){
<option>val</option>
}
</select>
You can set the id of the option equal to the value of each item in the enum, and pass it to the controller.
EDIT: To directly answer your questions:
You can store them as lookups in the db, but for small unlikely to change things, I usually just use an enum, and save a round trip.
Also look at this approach, as it looks better than mine:
Converting HTML.EditorFor into a drop down (html.dropdownfor?)

Html.Editor() helper in ASP.NET MVC 3 does not work as expected with array in model

In my ASP.NET MVC 3 application I have classes like the following:
public class Localization<T>
{
public int VersionID { get; set; }
public T Value { get; set; }
...
}
public class Localizable<T>
{
public Localization<T>[] Name { get; set; }
...
}
Then, I have the following view:
#model dynamic
...
#for (int i = 0; i < VersionCount; i++)
{
...
#Html.Editor(string.Format("Name[{0}].Value", i))
...
}
Now, when I display this view, passing a subclass of Localizable<string> as the model, the textboxes for the strings are rendered, but they are empty. If I replace #Html.Editor(string.Format("Name[{0}].Value", i)) with #InputExtensions.TextBox(Html, string.Format("Name[{0}].Value", i), Model.Name[i].Value), the textboxes are correctly filled with values from the model. However, using TextBox instead of Editor is not an option for me, because I want to use different editor templates for different types of T. So, what am I doing wrong, or is it a bug in MVC, and is there any workaround?
you can use attribute UIHint("MyUIHintName").
public class Localizable<T>
{
[UIHint("MyUIHintName")]
public Localization<T>[] Name { get; set; }
...
}
Then you need to create folder Views/Shared/EditorTemplates/. Next you need create Razor View
Views/Shared/EditorTemplates/MyUIHintName.cshtml
In this view you can write logic for every type, for example:
#model dynamic
#if(ViewData.ModelMetadata.ModelType.Name=="string")
{
//Do something
}
#if(ViewData.ModelMetadata.ModelType.Name=="int")
{
//Do something
}

Two render bodies in layout page?

I understand that only 1 RenderBody can exist in the MVC3 layout page however I want to attempt to create another. Maybe I'm looking at it the wrong way... Ideally I want to add a testimonial section that pulls in from the DB and display 1 testimonial at a time and a different 1 for each page refresh or new page. What is the best way to go about this?
Controller
CategoryDBContext db = new CategoryDBContext();
public ActionResult Testimonial(int id)
{
TestimonialModel model = db.Testimonials.Find(id);
return View(model);
}
Model
public class TestimonialModel
{
public int ID { get; set; }
public int CategoryID { get; set; }
public string Data { get; set; }
}
public class CategoryDBContext : DbContext
{
public DbSet<TestimonialModel> Testimonials { get; set; }
}
The View is in a folder called CategoryData.
You need to be use:
Layout:
#RenderSection("Testimonial", false) #*false means that this section is not required*#
and in you View
#section Testimonial{
}
I would use #Html.Action()
Here is a great blog post about using them: https://www.c-sharpcorner.com/article/html-action-and-html-renderaction-in-Asp-Net-mvc/
This would allow you to have a TestimonialController that can take in values, query for data and return a partial view.

Returning a specified type from a method with EF

How can I return return a collection in a method from a LINQ query that has a one to many relationship?
For instance, I have the following code where I can have many Projects to a TimeTracking object. Will the type that I have defined for the return type (IEnumerable) work? It is set up in my EF model as this specific kind of relationship.
public IEnumerable<TimeTracking> GetTimeTrackings()
{
YeagerTechEntities DbContext = new YeagerTechEntities();
DbContext.Configuration.ProxyCreationEnabled = false;
DbContext.Configuration.LazyLoadingEnabled = false;
var timeTrackings = (from timeTrackingProjects in DbContext.TimeTrackings.Include("TimeTrackings.Projects")
select timeTrackingProjects).Where(p => p.TimeTrackingID > 0);
CloseConnection(DbContext);
return timeTrackings;
}
If so, when I display it in my MVC 3 View, and my View contains an IEnumerable<YeagerTech.YeagerTechWcfService.TimeTracking> model, will the model variable have records in it for the TimeTracking and Project objects? I don't think it will. My TimeTracking object is set up as follows unless I need to inherit the Project class with it (which would then have the Project properties):
public partial class TimeTracking
{
[DataMember]
public int TimeTrackingID { get; set; }
[DataMember]
public short ProjectID { get; set; }
[DataMember]
public byte[] Attachment { get; set; }
[Required]
[DataType(DataType.Date)]
[DataMember]
public System.DateTime StartDate { get; set; }
[Required]
[DataType(DataType.Date)]
[DataMember]
public System.DateTime EndDate { 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 Project Project { get; set; }
}
I also want my View to display the Project text that is associated with the TimeTracking and not the Project value. How can I do this?Can someone please help?
I got the following msg from invoking a method on my WCF client.
'cannot be serialized if reference tracking is disabled'
After getting the msg, I then modified my DataContracts to include references ([DataContract(IsReference = true)]).
namespace YeagerTechModel
{
[Serializable]
[DataContract(IsReference = true)]
public partial class Customer
{
public Customer()
{
this.Projects = new HashSet<Project>();
}
[DataMember]
public short CustomerID { get; set; }
[Required]
[StringLength(50)]
[DataType(DataType.EmailAddress)]
[DataMember]
public string Email { get; set; }
I am executing the following server side code to successfully get data from my database in a parent/child relationship. The Include method explicity invokes getting the related Project data for the specific Customer. I had to do it this way because you must turn LazyLoading off if you want to get your parent/child data across the wire.
If I look at the WCF messagelog, I can see the actual data coming across in a Customer object and it has the Project object inside of the Customer object.
However, after the call is made and I actually inspect the contents of the "customer" variable, I don't see any refernces to any Project data.
public IEnumerable<Customer> GetCustomers()
{
YeagerTechEntities DbContext = new YeagerTechEntities();
DbContext.Configuration.ProxyCreationEnabled = false;
DbContext.Configuration.LazyLoadingEnabled = false;
IQueryable<Customer> customer = DbContext.Customers.Include("Projects").Where(p => p.CustomerID > 0);
CloseConnection(DbContext);
return customer;
}
The thing I want to do now, is reference the Project data coming back from the call. However, I don't get any Customer object intellisense after typing "customer.". It's all pertains to an IQueryable object.
I'm passing it back into my MVC Controller as the following type:
IEnumerable<YeagerTechWcfService.Customer> customerList = db.GetCustomers();
and into my View as the following model:
IEnumerable<YeagerTech.YeagerTechWcfService.Customer>
Now, the big question is "How can I reference the Project data coming back in my View?
The below is my code for the View, but there is no intellisense for "item.Project". Note that "Email" is a property inside my Customer object.
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
Looks like your Linq query should be closer to this (NOTE: did not test the query, might need tweaking):
var query = (from tt in DbContext.TimeTrackings.Include("Projects")
where tt.TimeTrackingID > 0
select tt).ToList();
Linq query as you have written is deferred execution, you are closing your connection before retrieving the data, so that would probably cause a runtime error.
.Include() statement should specify the property on the entity (TimeTracking in your case) that need to be loaded, so in this case that would be Project property
Once you have retrieved your enumerable collection of TimeTracking entities you can access the properties of the Project entity associated with a particular TimeTracking entity like so:
foreach(var tracking in GetTimeTrackings())
{
foreach(var project in tracking.Projects)
{
// Assuming your Project entity has a Name property
Response.Write(project.Name);
}
}
I'm not sure what you mean by
I also want my View to display the Project text that is associated
with the TimeTracking and not the Project value.
can you clarify what property from which entity you want to see? What is the Project Entity definition?
In response to your comment about closing connection after retrieving the data:
The statement IQueryable<Customer> customer = DbContext.Customers.Include("Projects").Where(p => p.CustomerID > 0); does not actually execute a query against the database until you start to iterate it (most likely in your view with a foreach statement). If you add a .ToList() at the end of that statement, it will execute it and return a List<Customer> (which is also IEnumerable) which contains all the records that are result of your query.
When you try to type customer. to get intellisense for the Customer entity, you're not seeing it because customer is a list of Customer entities (or rather an IQueryiable of them) so you would need to do something like customer[0]. to access the properties of the first Customer entity in that list (or iterate over it).
I'm not 100% sure how entity references come through in ASP.NET MVC on a model entity but a really simple way you can get this done is create a model class you want to use in your view, say something like this:
public class TimeTrackingModel {
public int TimeTrackingID { get; set; }
public string ProjectName { get; set; }
}
then in your query do this:
var customers = (from tt in DbContext.TimeTrackings.Include("Projects")
where tt.TimeTrackingID > 0
select new TimeTrackingModel { TimeTrackingID = tt.TimeTrackingID, ProjectName = tt.Project.ProjectName }).ToList();
then in your view specify IEnumberable<TimeTrackingModel> as the model and then access the properties like this:
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProjectName)
</td>
Actually, after further review, I can now see the Project collection in my Customer collection all the way back up to my client after adding a QucikWatch on the object.
The correct answer is the last part of my post where the LazyLoadingEnabled = false appears.

Resources