Viewmodel set up Aspt.net MVC 6 - asp.net-mvc

I'm having trouble understanding how to implement a ViewModel in Asp.net MVC, I have the following tables:
Form
ID, Data
Report
ID, FormID, Owner, Category, Status, SubmissionDate
ReportValues
ID, ReportID, Title, Value
I'm looking for a way to display and edit Report and ReportValues in the one ViewModel where ReportValues.ReportID = Report.ID
ReportValues will have multiple entries that relate to a Report.
I have had a look at similiar questions on here and tried following a tutorial ( http://techfunda.com/howto/262/list-data-using-viewmodel ) and coming up empty handed.
If you need any more information let me know and thanks in advance for any replies!

Your View Model is nothing more than a class. You can solve this many ways, but here's an example.
Create your 3 classes like you normally would.
public class Form
{
public int Id { get; set; }
public string Data { get; set; }
}
public class ReportValues
{
public int Id { get; set; }
public int ReportId { get; set; }
public string Title { get; set; }
public string Value { get; set; }
}
public class Report
{
public int Id { get; set; }
public int FormId { get; set; }
public string Owner { get; set; }
public string Category { get; set; }
public string Status { get; set; }
public DateTime SubmissionDate { get; set; }
}
Then, create your ViewModel class to include the three above classes like this.
public class ReportViewModel
{
public Form Form { get; set; }
public ReportValues ReportValues { get; set; }
public Report Report { get; set; }
}
In your view you can access your three classes and their properties as you would in your controller. Model.Form.Id
Depending on your data types, ReportValues will likely be a property of Report, but that's entirely up to your data structure. You will need to populate the classes using whatever method you want (Entity Framework, ADO, etc.) before you can pass them to your view and use them.

Related

Using template for creating view for select stored procedure

I have a controller for select stored procedure. Now I am trying to add view for this controller using template.
Controller code block
public ActionResult Display()
{
return View(db.P_GET_USER().ToList());
}
This is the code block of context class for the stored procedure:
public virtual ObjectResult<P_GET_USER_Result> P_GET_USER()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<P_GET_USER_Result>("P_GET_USER");
}
Code block of P_GET_USER_Result.cs complex type:
public partial class P_GET_USER_Result
{
public string USERNAME { get; set; }
public string NAME { get; set; }
public int ROLE { get; set; }
public int STATUS { get; set; }
public string CREATED_DATE { get; set; }
}
When I try to create view keeping template as list and modal class as P_GET_USER_Result (final.Models), I get a pop up error
Unable to retrieve meta data for P_GET_USER_Result. One or more validation errors were detected during model generation
Please see the attached screenshot for the detailed error message.
When I searched the internet for tutorials, I found most of them show are creating empty template and then adding content in view. So can't I use list template. Please help.
Following your error, your Entity must have a key. You should change your Models:
public partial class P_GET_USER_Result
{
[key]
public int Id {get; set;}
public string USERNAME { get; set; }
public string NAME { get; set; }
public int ROLE { get; set; }
public int STATUS { get; set; }
public string CREATED_DATE { get; set; }
}
You can choose any fields set to key, but it's must identify.

ASP.NET MVC create a view with a model class containing complex objects

I am trying to create a view (with Razor engine) by mapping the model class to Person class through the Add View option in Visual Studio 2013.
When it creates a view it only creates Age, Gender, Name fields. However, I need a view which would list down all the properties in each class; i.e. I need a view which contains the following fields: Age, Name, Gender, EmployerName, Salary, City, State, and Country.
I have a a class similar to this:
public class Person
{
public int Age { get; set }
public string Gender { get; set; }
public string Name { get; set; }
public JobDetails JobDetailsInfo { get; set; }
public Address AddressInfo { get; set; }
}
public class JobDetails
{
public string EmployerName { get; set; }
public string Designation { get; set; }
public int Salary { get; set; }
}
public class Address
{
public string City { get; set; }
public string State { get; set; }
public int Country { get; set; }
}
As your relationships are 1:1, this is pretty straight-forward.
You'll have to manually edit the view. Assuming the Model is of type Person, here's an example row:
<tr>
<td>#Model.Age</td>
<td>#Model.Name</td>
<td>#Model.Gender</td>
<td>#Model.JobDetailsInfo.EmployerName</td>
<td>#Model.JobDetailsInfo.Salary</td>
<td>#Model.AddressInfo.City</td>
<td>#Model.AddressInfo.State</td>
<td>#Model.AddressInfo.Country</td>
</tr>
This will work as long as you have that simple relationship, but if what you've shown does not correctly represent any normalisation you've applied to the data structure, this will fall flat on its face.
create the view manually or use inheritence...something like
public class jobdetails : person
{
}
I slightly changed my class structure and i created partial views for commondata,jobdetails and address and used them in my main view using #Html.Partial. I was able to pass default data by creating an object instance and loading some default values and passed the entire object to the view .The catch here is the model class which is bind to the Parent view must conatin all properties which are used for creating partial views. Pls see below
Controller method:
//Assign all properties for person object here
return View("ViewName", "PersonObject");
.cshtml:
#Html.Partial("ViewPath",Model.Data)
#Html.Partial("ViewPath",Model.JobDetailsInfo )
#Html.Partial("ViewPath",Model.AddressInfo )
public class Person
{
public CommonData Data
public JobDetails JobDetailsInfo { get; set; }
public Address AddressInfo { get; set; }
}
public class CommonData
{
public int Age { get; set }
public string Gender { get; set; }
public string Name { get; set; }
}
public class JobDetails
{
public string EmployerName { get; set; }
public string Designation { get; set; }
public int Salary { get; set; }
}
public class Address
{
public string City { get; set; }
public string State { get; set; }
public int Country { get; set; }
}

MVC 5 Model. Set Property to Database or Entity Framework value

The model Survey CRUD's the Questions:
public class Survey
{
public int SurveyID { get; set; }
public string Question1 { get; set; }
public string Question2 { get; set; }
public string Question3 { get; set; }
public string Question4 { get; set; }
public string Question5 { get; set; }
}
This model IntroResponse should have Properties that should be set to the values set in Survey. (IntroResponse is read only, not Creating or Editing Question properties):
public class IntroResponse : IValidatableObject
{
public int IntroResponseID { get; set; }
public int SurveyID { get; set; }
[ForeignKey("SurveyID")]
public virtual Survey Survey { get; set; }
public string Question1 { get; set; }
public string Question2 { get; set; }
public string Question3 { get; set; }
public string Question4 { get; set; }
public string Question5 { get; set; }
public IntroResponse()
{
//Code here?
}
As you can see these two models have a realtionship that is:
SurveyID 1 -----> * IntroResponse
But I want to inherit more properties from the Survey model. Is this possible without adding Controller code at all?
Shall I retrieve this information via Entity Framework or simply get values from Database?
I could not find any earlier threads about this specific question. I really looked.
Please give me an idea about what is the best practices to achieve this.
Update:
What I want to have is the Questions automatically retrieved and displayed when I select SurveyID with the dropdown. This would require client-side code, right? So should I have JavaScript code make a database call to get the Questions? I don't want to mix JavaScript and C#/Razor code in this way. That is why I am asking for some pointer!

Entity Framework defining tables in db context

I am buys designing the model below:
public class LogModel
{
public class UserActivityLogs
{
[Key]
public int id { get; set; }
//Id of the user
public string userId { get; set; }
//Time of the log
public DateTime time { get; set; }
public LogActions action { get; set; }
}
// Types of actions to log
public class LogActions
{
[Key]
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
}
}
Now what I would like to know is do I need to add a table in the context for Logactions as well as UserActivityLogs or will EF see that the two tables are linked and create the log action table automatically?
Also have I specified my relationships correctly? What I was aiming for is that I can define multiple types of Logactions and then a userlog will then have a single log action associated to it.
First, don't use nested classes, it's a needless complication. Use namespaces to organize classes.
Second, don't use plural names for classes. One instance of class represents one entity. Also, use CamelCase names for properties.
Third, yes, Entity Framework will be aware of the associations between the two classes and create a database model with two tables and a foreign key.
So this leaves you with:
namespace MyApp.LogModel
{
public class UserActivityLog
{
[Key]
public int Id { get; set; }
public string UserId { get; set; }
public DateTime Time { get; set; }
public LogAction LogAction { get; set; }
}
public class LogAction
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}

How to map a list of checkboxes options to a model first class?

I have this list of options in my web form:
And I want to work with model-first. But I'm very noob with MVC and Model-first, so I don't know how to better represent this in my model class.
Should I make one attribuite for each item? Or should I make an array where each position is one option (maybe using enums)?
public bool[] Comportamento { get; set; }
// or
public Comportamento[] Comportamento { get; set; }
// or
public bool Manso { get; set; }
public bool Arisco { get; set; }
...
You should have a class CompartamentoViewModel that looks like this:
public class CompartamentoViewModel
{
public int Id { get; set; }
public string Description { get; set; }
}
Then, in your main view model:
public class MyViewModel
{
// List of all objects for the view
public List<CompartamentoViewModel> Compartamentos { get; set; }
// List of ints to retrieve selected values
public List<int> SelectedCompartamentos { get; set; }
}
In the view, use the description for the text and the ID for the value. In the post, populate SelectedCompartamentos with the list of selected IDs.
Disclaimer: I have no idea how to pluralise "Compartamento."

Resources