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);
}
}
Related
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.
I am trying to implement view model to get the data from multiple table. However, I am getting the following error
InvalidOperationException: The entity type 'RoleManagement.Models.RolePermissionsViewModel' requires a key to be defined.
Below is my view model
public class RolePermissionsViewModel
{
public List<LMS_RolePermissions> RolePermissions { get; set; }
public List<LMS_UserPermissions> UserPermissions { get; set; }
}
Where LMS_RolePermissions and LMS_UserPermissions are two different tables in the database. Basically I want to get the data from these two tables in view model. To get the data I have written below code
RolePermissionsViewModel rolemodel = new RolePermissionsViewModel
{
RolePermissions = dbContext.RolePermissions.ToList(),
UserPermissions = dbContext.UserPermissions.ToList()
};
and DBContext class
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<LMS_LocLanguage> LMS_LocLanguage { get; set; }
public DbSet<LMS_Permissions> Permissions { get; set; }
public DbSet<LMS_RolePermissions> RolePermissions { get; set; }
public DbSet<LMS_UserPermissions> UserPermissions { get; set; }
public DbSet<RolePermissionsViewModel> RoleUserPermission { get; set; }
}
I do not want to Key to be defined and table should NOT be created.
How can I solve this problem ?
it is advised to place seperately your domainmodels and viewmodels. all tables in the applicationcontext are created by entity framework convention if if i use DbSet<myclass> or mention it in another class that used with Dbset. your answer should be excluding types with data annotations NotMapped and with fluent api modelbuilder.ignore<RolePermissionsViewModel>();. (of course,you will remove DbSet firstly. if i read and understand correctly, you say to your codes "please dont create this,i beg on you" after you command database to set.)
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
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.
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