Working with EF Generated Model and My Own Model - c#

I have 2 Models. First one is created by EF and looks like:
public partial class PrinterMapping
{
public string MTPrinterID { get; set; }
public string NTPrinterID { get; set; }
public string Active { get; set; }
}
I created the second one (nothing to do with any database table) and looks like:
public class ExceptionModel
{
public string ExceptionMessage { get; set; }
public ExceptionModel(string exceptionMessage)
{
ExceptionMessage = exceptionMessage;
}
}
In my Index and Create views, the model that is automatically being passed is PrinterMapping. I wish to output ExceptionMessage property of the ExceptionModel model after populating it in a relevant way after saving to the table accessed by PrinterMapping. So in my Create controller, I am doing:
ExceptionModel exModel = new ExceptionModel(message);
where message parameter is a relevant string like "Printer X already exists".
My thoughts were to have a partial view called ExceptionMessageView where my ExceptionModel would be passed on to it and I will display:
#Html.DisplayFor(model => model.ExceptionMessage)
And in my Index and Create views, I will have a line like:
#Html.Partial("~/Views/Home/ExceptionMessageView.cshtml")
Am I over complicating things? This isn't working anyway since I don't fully understand how to pass on the populated ExceptionModel from my Create Controller to the ExceptionMessageView partial view.
Will a kind soul please enlighten?

I would have a complex Viewmodel "PrinterViewModel" that has properties for ExceptionModel and PrinterMapping.
The controller then passes the complete PrinterViewModel to the view.
In the View you would render partials by passing part of the complex Viewmodel to them.
#Html.Partial("ExceptionMessageView",Model.Exception)

Related

How do I 'inherit' a class properties to use with Entity Framework

I want to add a new property on my class, make it strongly typed so I can use it in my views and controllers, I've tried to inherit the properties, but Entity Framework or C# throws me errors...
I have this class:
public class Patient
{
public int Id { get; set; }
public string Message { get; set; }
public string FirstName { get; set; }
.....
}
which has a lot more properties in it, but shortened here.
I have a razor view, which is uses 'Patient' as it's model
using model Project.Models.Patient
So I had completed my view (or so I thought) and was asked to add functionality in the view. The functionality is to send a POST using a form of a 'Message' (a simple textarea in html). I've already got all the details I want, but this new 'Message'
So I thought, because I don't want this field in the database I could add it like this:
public class Patient
{
public int Id { get; set; }
public string Message { get; set; }
public string FirstName { get; set; }
[NotMapped]
public string Message { get; set; }
.....
}
But I'm not a fan of this, it doesn't relate to the Patient in any other way.
So I thought I could change my model in razor to something like this:
#model Project.Models.DTOs.PatientMessage
and inherit the Patient class and all it's properties (so I don't have to retype and copy past the fields again) and the new PatientMessage class would look like this:
public class PatientMessage : Patient
{
public string Message { get; set; }
}
But when I refresh my application, I receive a message stating the Application Database Context has changed, and I have to update this. I don't want to update my database, and I can't really see why I need to, it's an extra field which I don't want to include in my database.
So then I decided to make this class an 'abstract' class
public abstract class PatientMessage : Patient
{
public string Message { get; set; }
}
When I refreshed my page this time, I saw no need to update the Database, great I thought, and when I went near a page where the model was
#model Project.Models.Patient
I received this message
The abstract type 'Project.Models.DTOs.PatientMessage' has no mapped descendants and so cannot be mapped. Either remove 'Project.Models.DTOs.PatientMessage' from the model or add one or more types deriving from 'Project.Models.DTOs.PatientMessage' to the model.
MY QUESTION
Can I include this one field, without placing it on the Patient class, ideally without having to update models in my razor views, or would I have to change the models in the views and controllers and update the information to include the message and map all the details from a 'PatientMessage' to a 'Patient'
Please let me know if you need any further information.
Regards

Is it OK to return Model object to View in MVC?

Is it right if I return a Model object from Controller method to the View to be able to set the datasource to the datagridview in the View?
I'm trying to use MVC in WinForms.
I have a wrapper class that holds two models and which I pass to the Controller.
public class TwoModels
{
public UserInfo user { get; set; }
public List<UserInfo> Users { get; set; }
public BindingList<MedicineProduct> Products { get; set; }
}
I have a method in my View which loads data and sets the DataGridView's datasource.
private void LoadCache()
{
productsCache = new Products();
productsCache = XMLToObjectToXML.LoadData(productsCache, path);
dataGridView2.DataSource = productsCache.Products_;
userCache = XMLToObjectToXML.LoadUser(username);
}
I want to move this method to controller. But, I don't know if it's a right approach. Should I load data in controller or should I do it inside wrapper class?
Yes. Ensure that the ActionResult method has the same name as a view you want to return and that the view is expecting a Model object the same type as you are returning in the controller.
I would need to see some example code to help determine what you plan on achieving with use of datagridview.

Join two models to get data into a view

Complete MVC Noob warning.(2 hours learn time)
I've looked at a lot of MVC3 examples online but I havent found a simple example to do what I am trying to do.
What I want to do is two join two models and get some data into a view. The most obvious
public partial class Model1
{
public int ID { get; set; }
public int StudentID { get; set; }
public int CoachID { get; set; }
public String StudentName {get;set;}
}
public partial class Model2
{
public int CoachID { get; set; }
public String CoachName { get; set; }
}
Basically in my view I have to just join Model 1 and model 2 on CoachID and print
StudentName and CoachName in a grid.
How do I do this? How do I create the view model for this ?
How do I iterate through the view and print the joined data?
Can I instead just create a view in the database and directly attach a model and a view to it ?
Sounds simple, but Ive spent the last three hours online completely baffled
Create a StudentCoachViewModel with exactly the properties you need in it to display, nothing more, nothing less.
Populate a list of this viewmodel in your controller and send it to your view. Code sample to follow shortly.
Enumerate that list in your view
public class StudentCoachViewModel
{
public string CoachName { get; set; }
public string StudentName { get;set; }
}
In your controller something along the following lines (just typing this out, haven't checked in compiler)
public ActionResult Index()
{
//code to populate your model1 and model2 already assumed
var viewModels = (from m in model1List
join r in model2List on m.CoachId equals r.CoachId
select new StudentCoachViewModel(){ StudentName=m.StudentName,
CoachName = r.CoachName }).ToList();
return View(viewModels);
}
In your view, something along the lines of (clearly you want to format and use proper layout, table, etc which can be auto generated by visual studio)
#model IEnumerable<StudentCoachViewModel>
//other html content here
#foreach(var viewModel in Model)
{
#Html.DisplayFor(o=>o.CoachName) #Html.DisplayFor(o=>o.StudentName)
}
Now if you are only wanting a single one here rather than a list its even easier
public ActionResult Index(int id)
{
//code to load model1 and model2 already assumed to be in place. also assuming you loaded this data from a database by the id field being passed into this method.
return View(new StudentCoachViewModel(){ StudentName = model1.StudentName, CoachName = model2.CoachName});
}
And the view becomes then simply
#model StudentCoachViewModel
//other html here, h1, divs, etc whatever is in your view as html content.
#Html.EditorForModel()
or if you like to display each one instead of the above one line call:
#Html.LabelFor(o=>o.CoachName)
#Html.EditorFor(o=>o.CoachName)
try this
public partial class Model3{
public Model1 model1{get;set;}
public Model2 model2{get;set;}
}
bind Model3 into view.
View page can accept only one model, so you can't pass two model at the same time,
So you have to Create a another model with all the members of that two model...
then in controller, you should convert those two model to one model and pass it to view with help of new model one
or else you can create a another new model with those two model

Which is the best way to use multiple models with sames properties and using a unique view?

For example, I have 3 models with an Id (int), a Name (string) and an active (bool). It's possible to use just one view for these models with the same properties ? A technique like a generic object ? Inheritance ? It's to avoid to write multiple views with the same HTML code.
You could create a ViewModel.
For sample:
public class CustomerViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
And create another ViewModel with a type like this:
public class CustomersViewModel
{
public CustomerViewModel Customer1 { get; set; }
public CustomerViewModel Customer2 { get; set; }
public CustomerViewModel Customer3 { get; set; }
}
and type your view with this type:
#model CustomersViewModel
Or just use an collection to type your view
#model List<CustomerViewModel>
Take a look at this anwser!
https://stackoverflow.com/a/694179/316799
In a view you can either
specify shared base class for all models and use that.
use dynamic as model
split view in shared (extract into separate view) and specific part. Than call shared sub-view with either existing model (if using base class/dynamic) or simply new model constructed based on data in specific model.
Sample of extracting shared portion with inheritance. Using Html.Partial to render shared portion:
class SharedModel { /* Id,...*/ }
class SpecificModel : SharedModel { /* Special... */ }
SpecificView:
#model SpecificModel
#Html.Partial("SharedView", Model)
<div>#Model.Special</div>
SharedView:
#model SharedModel
<div>#Model.Id</div>
Side note: You can specify view name when returning result by using View if view name does not match action name:
return View("MySharedView", model);
In ASP.NET MVC4 you have the opportunity not to define a model for the view. This means leave the definition of the model empty (don't use #model MyNamespace.MyClass) and then it will automatically use "dynamic" as model.
Greetings
Christian

ASP.NET MVC Forms for Model

I'm trying to learn MVC by building a full-featured website. I'm a little stuck when it comes to dealing with forms, and posting data, and models....
BTW: I'm using EF Code-First w/MS SQL CE
Here's the Models in question:
public class Assignment
{
public int AssignmentID { get; set; }
public int? CourseID { get; set; }
public string Name { get; set; }
// etc...
public virtual Course Course { get; set; }
}
public class Course
{
public int CourseID { get; set; }
// etc...
}
I'm loading a partial view that allows the user to add a new assignment
Controller:
public ActionResult Assignments()
{
var assignments = myContext.Assignments.OrderBy(x => x.DueDate);
return View(assignments);
}
[HttpPost]
public ActionResult AddAssignment(Assignment assignment)
{
myContext.Assignments.Add(assignment);
myContext.SaveChanges();
return RedirectToAction("Assignments");
}
// Returns a strongly-typed, partial view (type is Assignment)
public ActionResult AddAssignmentForm()
{
return PartialView();
}
Here's where I'm stuck: I want this form to have a drop down list for the different courses that an assignment could possibly belong to. For example, an assignment called "Chapter 3 Review, Questions 1-77" could belong to course "Pre-Algebra". However, if I use the code below, I have to explicitly declare the SelectListItems. I thought that with the given Assignment model above, I should be able to have the drop down list for Courses automatically generated using MVC awesomeness. What am I doing wrong?
AddAssignment Partial View:
#model MyModels.Assignment
#using(Html.BeginForm("AddAssignment", "Assignments"))
{
// Can't I create a drop down list without explicitly
// setting all of the SelectListItems?
#Html.DropDownListFor(x => x.Course, ....
}
Basically you are confusing/mixing your business model and your UI model.
The quick fix here is to add the data for the dropdown list to the ViewBag (a dynamic object).
Alternatively you could create a class AssignmentModel that contains the relevant Assignment properties and the List.
And No, this is not well supported in the templates.
You do realize you'll need some error handling in the Post method(s)?

Categories

Resources