Displaying multiple lists of data in a view (i.e. CustomerContacts, CustomerLocations) - asp.net

I have a CustomersController and in the Detail.cshtml view I need to display a list of that Customer's contacts and a list of that Customer's locations. I have a Detail(int? id) ActionResult and I have access to my CustomerService from within the controller. As of now in my Detail ActionResult I am able to do:
var cust = _custService.GetCustomerById(id);
return View(cust);
How would one recommend getting the rest of my lists in the view. I think I will create a GetContacts(customerID), GetLocations(CustomerID) within my CustomerService and then call them just like I call GetCustomerByID above. If I were to do it this way how would I have access to these lists in my view.
The next thing I was thinking about was possibly creating a ViewModel that has all of the basic customer properties like customer.Name, customer.Phone but then trying to figure out how I also make sure the ViewModel has the customer's contacts and locations. Would I just add 2 more properties to the ViewModel like customer.contacts and customer.locations since EF6 will make them available to me?
Any suggestions on the best way to go about getting multiple lists of information related to an entity in a view? Customer contacts and Customer locations are both one-to-many

The best practice is using a view model to transfer the data, as you have thought about.
public class CustomerDetailViewModel {
public string Name { get; set; }
public string Phone { get; set; }
public List<Contact> Contacts { get; set; }
public List<Location> Locations { get; set; }
}

Related

How do I populate my model from a database entry?

I have set up a large form with lots of entries. It populates my model and then saves to the database. I also need to be able to pull this information out of the database, put it into the model, and populate a bunch of fields with it for review. How do I do this?
Using ASP.NET MVC 4 Razor.
var db = new TechProjPlansContext();
TechProjPlan model = new TechProjPlan();
I can set up my data context and model, but where do I go from here to populate the model with a data entry chosen by ID?
You can search by givenId and if found return result type of TechProjPlan otherwise null
var resultFound = db.TechProjPlans.Where(e=>e.Id = givenId).FirstOrDefault();
I strongly recommend following this tutorial step by step. From the tutorial to answer your question:
Write a Model class like:
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
Add a DbSet to your Context class: (TechProjPlansContext in your project)
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
Make sure you can connect to the database server, check your connectionStrings in your Web.config file.
As you wanted to filter only one Entity by using ID, you need a Controller class:
public ActionResult Details(int id = 0) // here id is set to 0 if it's null
{
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
As you see, you'll be returning View(movie), that means you return Details page with the Entity (a movie) you got from the database. And have a View, that renders to actual HTML code the client will see. At the top of it, add the line:
#model MvcMovie.Models.Movie // (something TechProjPlans.Models.Movie in your project)
#Html.LabelFor(model => model.Title)
This will create a simple text showing the movie's title.
It's not logical to go deeper within an answer, so rest is up to you with that tutorial. Just keep in mind that the code above is only one example and you can use endless variations within each level for your situation.
You can right click on the directory Controllers, select Add New and select your Model class and Context class at the page. That will produce a Controller and Views (index, edit, delete, details, insert) tied to it which will be a good way to start your MVC study.

Save two Entities from one View

How to save two Entities from one View. Suppose I have two Entities Party and Person with One to Many relation. Now I need to save both Entities from Party View. I am using ASP.NET MVC4.
public partial class Cm_Opt_Pty_Party_S
{
public Cm_Opt_Pty_Party_S()
{
this.Cm_Opt_Psn_Person_S = new HashSet<Cm_Opt_Psn_Person_S>();
}
public int Pty_ID { get; set; }
public Nullable<int> Pty_PARTYTYPECODE { get; set; }
public string Pty_FULLNAME { get; set; }
public string Pty_GOVTID { get; set; }
public Nullable<int> Pty_GOVTIDTC { get; set; }
public Nullable<int> Pty_GOVTIDSTAT { get; set; }
public virtual ICollection<Cm_Opt_Psn_Person_S> Cm_Opt_Psn_Person_S { get; set; }
}
What you can do is create a ViewModel This class would contain the relevant properties needed to create both entities.
Then you base your View on the ViewModel instead, and pass that to the controller.
When you want to save the entities, you can build up the separate entities and save them.
I have a better understanding of your issue, so editing this answer to show the solution I would use.
Your Controller will deliver the Party object to your view for displaying the Party information. Using a loop you can display the items contained in the collection.
#foreach(var m in Model.Persons)
{
#Html.DisplayFor(model=>m.FirstName)
#Html.DisplayFor(model=>m.Surname)
}
When you want to add more items into the collection, you will need to render a partial view or new view containing a form for adding a Person. It will be strongly typed as Person model and the Controller action recieving the post will be expecting a Person
If for example a Person just had a FirstName,Surname and PartyId the form would use these helpers in your view
#Html.TextboxFor(m=>m.FirstName)
#Html.TextboxFor(m=>m.Surname)
#Html.TextBoxFor(m=>m.PartyId)
You then submit that back to your controller, and have logic for adding the person to the collection. Then return the view with Party model containing the newly added Person in the Persons collection.
Using #Ajax.BeginForm or some custom Jquery/Javascript you could handle this async to prevent page refreshing during the process.
If you don't want to do it this way, another option is EditorTemplates. See here for example: ASP.NET MVC LIST and Create in same view

How to preserve input ids when editing lists in ASP.NET MVC?

I'm working with ASP.NET MVC 4, but I on't think that matters for the purpose of this question.
I have a relatively complex model for my edit view. Like this:
public class Recipe_model
{
public string Name { get; set; }
public List<Recipe_Ingredient_model> Ingredients { get; set; }
}
where Ingredients is
public class Recipe_Ingredient_model
{
public int RecipeID { get; set; }
public int? UnitID { get; set; }
public double? Quantity { get; set; }
public Ingredient_model Ingredient { get; set; }
}
which itself contains the Ingredient model.
When I make a form for this, the built-in Html.EditorFor() doesn't work for anything past the properties of the Recipe_model, so I'm using partial views to display the editor for each of the sub-models.
That works fine as far the interface goes, but when I submit the form to the controller and try to bind to the Recipe_model automatically using
[HttpPost]
public ActionResult Edit(Recipe_model model)
{
return View(model);
}
it fails because the ids of the input elements in the partial views do not conform to the correct pattern (I think ParentModel_Property).
Short from hard-coding the ids in the partial view or binding manually from the FormCollection in the controller, is there some way to get the correct ids generated in the partial view so that the model will bind automatically on submit?
This is common problem. Instead of simple partials, use EditorTemplates (special folder for models) and binding will work automatically.
For example look at this question: Updating multiple items within same view
in addition to the answer given by #WebDeveloper
you can also try and create a custom model binder though a little more complex but will add to the ease of posting and binding form value to the objects in long run
have a look here http://patrickdesjardins.com/blog/asp-net-mvc-model-binding
you will have to manually take all the form values and bind them to the model once and then you will be able to use the #HtmlFrom methods on the razor to do anything and you will get all the value inside the objects inside the action methods as you like.

Add items to a list in the a model that contains multiple lists in ASP.Net MVC 2

Ok, so this one has had me stumped for a few hours today. After trying to muster up a couple solutions, I can't seem to get it just right.
I have a model, which contains some primitive properties and some lists.
In the view, I need to be able to update any one of these lists (add / remove / update) without hitting the database and saving the changes. The save action will only happen when the save button is clicked on the page. There will be multiple forms on the page.
The forms are as follows....
The main form will just have name/description fields.
The other forms will contain the fields needed for the types in the lists.
Example Model
public class Model
{
public string Name { get; set; }
public string Description { get; set; }
public List<Type1> { get; set; }
public List<Type2> { get; set; }
public List<Type3> { get; set; }
}
After more failed attempts, I decided to do it this way:
I throw the Model into a Session variable. Then in the view I have two forms, one for each list. The forms submit to an action that retrieves the model from the session variable, inserts the record to the appropriate list, and returns the same view with the updated model.
Since using AJAX isn't a requirement, this works just how i need it to.

how to edit json data runtime?

i want to add the data to existing generated json data in my asp.net mvc application , what i have to do ?
means , suppose i have class Company that having list of Departments as property. but json serialization is not able to support such kind of circular reference. so i thought how if, i get serialize the Company object first without list of Departments, then get departments for each company and then serialize this list and append data to company serialized data. i know this may be wrong way . but i have to do because of time ultimatum. please guide.
You could define a view model where you won't have any circular references:
public class DepartmentViewModel
{
public string DepartmentName { get; set; }
}
public class CompanyViewModel
{
public IEnumerable<DepartmentViewModel> Departments { get; set; }
}
and then you would map between your model and view model (you could use AutoMapper for this) and finally return the view model to the view.
For example:
public ActionResult Index()
{
var companies = _repository.GetCompanies();
var companiesVM = Mapper.Map<IEnumerable<Company>, IEnumerable<CompanyViewModel>>(companies);
return Json(companiesVM, JsonRequestBehavior.AllowGet);
}
Now you no longer would have circular references and you will be able to successfully serialize the view model to JSON and you would only pass the information that is required to the view.

Resources