Razor view for a many to many relationship - asp.net-mvc-3

I have a very basic question with the Razor views.
I want to make a View for this model for creation and deletion.
Model is as follows
public class RolePriviledgeModel
{
[Key]
public int RolePriviledgeId { get; set; }
public RoleModel Role { get; set; }
public PriviledgeModel Priviledge { get; set; }
public ICollection<PriviledgeModel> Priviledges { get; set; }
}
I want to have two drop down list boxes for selecting the User ID and Role ID on the view.
How to get the role ids and priviledge ids from the DB Context and where to use the function?

Create a ViewModel which will have Users and priviledges as its properties. In your controller, fetch data from database , populate the View-model and finally send it to view.
Your view can display the drop down list boxes using '#Html.DropDownListFor()' method.
for example:
Your view model
public class UserRoleViewModel
{
int userId {get;set;}
SelectList Users{get;set;};
int RoldeId {get;set;}
SelectList Roles{get;set;}
}
In Your Controller:
UserRoleViewModel urvm=new UserRoleViewModel();
urvm.users= new SelectList(db.Users.ToList(), "UserId","UserName");
urvm.Roles= new SelectList(db.Roles.ToList(),"RoleId","RoleName");
return View(urvm);
In your View
#Html.DropDownListFor(model => model.UserId, Model.Users);
#Html.DropDownListFor(model => model.RoleId, Model.Roles);
Hope this helps. Good luck

Related

How to show two table in single view?

In asp.net core MVC I need to show two tables in a single view. I have one page and there is a submit button on click of that it will go to another view .there in need to show two tables. I want to use JSON. but from the controller, it returns view model .so how to convert view model data in JSON format to show it in an HTML table?
you can use the Viewbag into your controller to show two tables in one view.
keep this at the top of your view page
#using Newtonsoft.Json
And I think then you can do this which you want.
#Html.Raw(#JsonConvert.SerializeObject(ViewBag.something))
I don't know why you want to return json, the usual solution is to create a ViewModel.
public class Model1
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Model2
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ViewModel
{
public Model1 Model1 { get; set; }
public Model2 Model2 { get; set; }
}
Then you can return a ViewModel to the view.
If you need to return Json,please provide your class model and your view code.

Can I add a view based on a ViewModel and without a controller for the newly added view?

I am newbie to MVC3 and I wonder if this is even possible and good practice?
I have a model + view + controller which works fine. This view shows a list of people - I want to be able to click on a person's name and be redirected to a new view that will show that persons details. This new view only has a ViewModel, but no controller because I plan to pass in the object in the action.
The Person object contains all the properties my view needs to show:
#Html.ActionLink(item.Person.FirstName, "PersonDetails", item.Person)
Is this possible/good practice??
I believe you have an misunderstanding of how MVC works. Your ActionLink will ALWAYS redirect to a corresponding ActionMethod of a Controller. What you'll want to do is create an action method in your controller that accepts the necessary parameters and then returns to the View your ViewModel.
Here is a very quick example to get you started:
public class HomeController : Controller
{
public ActionResult List()
{
return View();
}
public ActionResult DetailById(int i)
{
// load person from data source by id = i
// build PersonDetailViewModel from data returned
return View("PersonDetails", PersonDetailViewModel);
}
public ActionResult DetailByVals(string FirstName, Person person)
{
// build PersonDetailViewModel manually from data passed in
// you may have to work through some binding issues here with Person
return View("PersonDetails", PersonDetailViewModel);
}
}
Not a good way to do it like you want to (in your original post). A view should always have a view model. A view model represents only the data that you want to have on the view, nothing more and nothing less. Do not pass your domail model to the view, but rather use a view model. This view model might contain just a portain of the properties of your domain model.
In your list view you probably have a grid, and next to each row you probably have a details link, or a link on the name (as you have it). When either of these links are clicked then you are directed to a details view. This details view will have its own view model with only the properties that you need to display on the details view.
A domail model might look something like:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string ExampleProperty1 { get; set; }
public string ExampleProperty2 { get; set; }
public string ExampleProperty3 { get; set; }
}
Let say you only want to display the person's id, first name, last name and age then your view model will look like this:
public class PersonDetailsViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
You don't need ExampleProperty1, ExampleProperty2 and ExampleProperty3 because they are not required.
Your person controller might look like this:
public class PersonController : Controller
{
private readonly IPersonRepository personRepository;
public PersonController(IPersonRepository personRepository)
{
// Check that personRepository is not null
this.personRepository = personRepository;
}
public ActionResult Details(int id)
{
// Check that id is not 0 or less than 0
Person person = personRepository.GetById(id);
// Now that you have your person, do a mapping from domain model to view model
// I use AutoMapper for all my mappings
PersonDetailsViewModel viewModel = Mapper.Map<PersonDetailsViewModel>(person);
return View(viewModel);
}
}
I hope this clears things up a little more.

How to access an association in view from one POCO with several references to another

Sorry about the title; couldn't think of a better one.
Any way, I'm accessing an associated property in my view like so:
#Model.Company.CompanyName // No problems here...
The model is a viewmodel mapped to an EF POCO. The Model has several properties associated to the Company table. Only one of the properties in the model share the same name as the PK in the Company table. All the other properties reference the same table:
public class MyModelClass
{
public int Id { get; set; }
public int CompanyId { get; set; }
public int AnotherCompanyId { get; set; } // References CompanyId
public int AndAnotherCompanyId { get; set; } // References CompanyId
public Company Company { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
}
I'm obviously missing something here.
How can I get the names of the other companies in my Model?
Any help is greatly appreciated.
The model is a viewmodel mapped to an EF POCO
I think you are confusing the notion of a view model. A view model is a class that is specifically designed to meet the requirements of your view. So if in your view you need to display the company name and not the company id then your view model should directly contain a CompanyName property. Or a reference to another view model (CompanyViewModel) which contains the name directly. It is then the responsibility of your controller action to query your domain models (EF entities) and aggregate them into a single view model tat will contain all the necessary information that the view requires.
Here's how a typical view model might look like:
public class MyViewModel
{
public CompanyViewModel Company { get; set; }
public CompanyViewModel AnotherCompany { get; set; }
public CompanyViewModel AndAnotherCompany { get; set; }
}
public class CompanyViewModel
{
public string Name { get; set; }
}
Where the data comes from in this view model is not important. You could have the Company property populated from your EF stuff, the AnotherCompany property populated from a XML file and AndAnotherCompany from WCF.

MVC3: update Model after adding two columns to the table

Hi I have a few more questions on MVC3 Model and App_data.
I want to add two columns to my table, say lat, and lon. I can do that from sql script.
But after adding these two columns, how can I update the Model so the new columns will be the members of the Model?
I have a list of articles I want to display, what's the reliable way to display them in one view, instead of creating one view for each article?
Thanks a lot!
Answer to question 1:
Simply update your view model to store the additional fields. For example:
public class IndexModel
{
//existing fields
public string Name { get; set; }
public string Address { get; set; }
//etc
//your new fields
public string lat { get; set; } //use the preferred type
public string lon { get; set; }
}
Then, in the controller action you can update the model with the new fields from the database using entity framework or however you choose to connect to the database.
public class HomeController : Controller
{
public ActionResult
{
IndexModel model = //retrieve model from database here...
return View(model);
}
}

Entity Framework 4 error

I have created MVC3 application using Entity Framework Code First method. My model is very simple:
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int YearsAtCompany { get; set; }
}
and context class is
public class EmployeeDB : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
and controller looks like this:
EmployeeDB context = new EmployeeDB();
public ActionResult Index()
{
return View(context.Employees);
}
}
I have created EmployeesDb.mdf and Employee table.
but I get this error:
The model item passed into the dictionary is of type 'System.Data.Entity.DbSet`1[DFEmployees.Models.Employee]', but this dictionary requires a model item of type 'DFEmployees.Models.Employee'.
[Updated]
#model DFEmployees.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
Please suggest solution.
It's looks like your view are waiting for a single employee, and you are triying to fill the view with a DBSet of employees.
To solve it, you can set the #model of the view to an IEnumerable of employees, or send only one employee to the view, depending of what are you showing in the view.
EDIT: I think this problem is not related with the previous one. Check this link, I hope it helps you: LINK
Your controller action returns a list of employees so adapt your model respectively in the view:
#model IEnumerable<DFEmployees.Models.Employee>
Or if you wanted to use a single employee make sure you pass a single employee to the view:
public ActionResult Index()
{
return View(context.Employees.FirstOrDefault());
}
and then you can have:
#model DFEmployees.Models.Employee

Resources