MVC view with two different models - asp.net-mvc-4

I have a view called AccountManager on this view I have a section to update your profile information and update your password.
Both functions require a different model. ManageUserViewModel and ChangePasswordViewModel.
On the AccountManager view, both sections are rendered via #Html.Partial.
When I try to display the page, I receive the following error: "The model item passed into the dictionary is of type 'WebUI.Models.ManageUserViewModel', but this dictionary requires a model item of type 'WebUI.Models.ChangePasswordViewModel'."
How can I render both views without receiving this error?

ViewModel:
public class AccountManagerViewModel
{
public ManageUserViewModel manageUserViewModel { get; set; }
public ChangePasswordViewModel changePasswordViewModel { get; set; }
}
The View:
#model AccountManagerViewModel
/*HTML CODE*/
#Html.RenderPartial("_PartialChangePassword", Model.changePasswordViewModel)
#Html.RenderPartial("_PartialManageUser", Model.manageUserViewModel)
So you just play with the viewModels. Remember that they can have anything you need in the view. Let me know.

Related

Pass Url Parameters to Action by Model in ASP.NET MVC 4

I want to assign my url parameters to Model properties, passed as a parameter to the associated Action. For example;
Say, my url is http://www.example.com/Item/Index?color=red&size=50
My action inside the controller is like below:
public class ItemController : Controller
{
public ActionResult Index(MyModel myModel)
{
//
return View(myModel);
}
}
I want to configure the model or whatever necessary so that my model takes the color and size as field values. The following didn't work:
public class MyModel
{
[Display(Name = "color")]
public string Color{ get; set; }
[Display(Name = "size")]
public string Size{ get; set; }
}
What would be the correct way to solve the problem?
Thanks for any suggestion.
Update
Well, yes! The code above would work correctly, because Url parameter names are the same as model property names. I should explain my problem exactly as I encounter for the next time, sorry.
I must correct a part of my question to make it clear. The url should have been: http://www.example.com/Item/Index?c=red&s=50 to detect the problem.
If the url is like that, the code would not work. Because Url parameters don't have the same name as Model properties.
Updated model is below:
public class MyModel
{
[Display(Name = "c")]
public string Color{ get; set; }
[Display(Name = "s")]
public string Size{ get; set; }
}
Try adding [FromUri] in front of the parameter.
public class ItemController : Controller
{
public ActionResult Index([FromUri] MyModel myModel)
{
// do something
return View();
}
}
debugging the issue
Here are some suggestions in debugging the issue, as it should work out of the box.
try binding to primitive types
public class ItemController : Controller
{
public ActionResult Index(string color, string size)
{
// do something
return View();
}
}
Try reading out of the request object directly
var size = this.Request["size"];
If either of those work there is an issue with your model binding.
Update
If you want to have the query string parameters different to the model in MVC you'll need to have a custom model binder. Take a look at Asp.Net MVC 2 - Bind a model's property to a different named value and http://ole.michelsen.dk/blog/bind-a-model-property-to-a-different-named-query-string-field.html which extends the answer a little.
https://github.com/yusufuzun/so-view-model-bind-20869735 has an example with some html helpers that could be useful.

method within model in MVC

I have a model in my MVC app, 'designation'. I have a method getdesig() to simply return all of the designations. I originally had this in my controller but moved to my model recently, with the aim of decluttering my controller and making it thinner. Is this model a logical place to put such a method?
public class designation
{
[Key]
public int DesignationID { get; set; }
public string DesignationName { get; set; }
public virtual ICollection<user> users { get; set; }
private ClaimContext db = new ClaimContext();
public List<designation> getdesig()
{
{
return (from c in db.designations
select c).ToList();
}
}
}
yes, however in more complicated scenarios where conditions exists the controller is the spot to determine "What" needs to be loaded or "how much" needs to be loaded based off the scenario/arguments. In this very simple example it is fine as you are just dumping all the data without regard to any context.
It is a good practice to keep your ViewModels as simple and specific to the View as possible, the ViewModel's job is to simply be a common store to drive the view. The view relies on the model to be set with the appropriate data, it is the job of the controller to determine context and what should be populated in the model.

MVC4 - Partial View Model binding during Submit

I have view model which has another child model to render the partial view (below).
public class ExamResultsFormViewModel
{
public PreliminaryInformationViewModel PreliminaryInformation { get; set; }
public string MemberID { get; set; }
public string MemberName { get; set; }
public int PatientID { get; set; }
public string ConfirmationID { get; set; }
public bool IsEditable { get; set; }
#region Select Lists
public SelectList ProviderOptions { get; set; }
#endregion
}
public class PreliminaryInformationViewModel
{
public string ProviderName { get; set; }
public string ProviderID { get; set; }
public string ServiceLocation { get; set; }
}
This PreliminaryInformationViewModel view model also used as a child models in another view model since this preliminary information can be updated at different pages.
So I created this preliminary information as a separate partial and to include in other pages.
#{Html.RenderPartial("_PreliminaryInformation", Model.PreliminaryInformation);}
Inside the partial
#model Web.Models.Preliminary.PreliminaryInformationViewModel
<div>
#Html.TextBoxFor(x => x.DateOfService })
</div>
But the problem is during submit this preliminary model is always null due to the reason HTML name attribute is always is rendered as
but when I pass the parent model to the partial as below.
#model Web.Models.Exam.ExamResultsFormViewModel
<div>
#Html.TextBoxFor(x => x.PreliminaryInformation.DateOfService })
</div>
Now the HTML element is generated as
<input type = 'text' name='PreliminaryInformation.DateOfService.DateOfService' id='PreliminaryInformation.DateOfService'>
and it binds properly during the submit.
I understand MVC bind the element value based on the name attribute value, but the second implementation would need me to create a multiple partial for each page, which I don't like.
So far I couldn't find a solution to work with the first implementation, is there way I can make preliminary information model value bind during submit with the first implementation.
I know its a bit late but it might help to someone
If you have complex model, you can still pass it into partial using:
#Html.Partial("_YourPartialName", Model.Contact, new ViewDataDictionary()
{
TemplateInfo = new TemplateInfo()
{
HtmlFieldPrefix = "Contact"
}
})
where I have defined model with property "Contact". Now what HtmlFieldPrefix do is add the property binding for each model "so the model binder can find the parent model"
There is a blog post about it: http://www.cpodesign.com/blog/bind-partial-view-model-binding-during-submit/
.NET Core 2 binding
In .NET Core 2 and MVC the answer above will not work, the property is no longer settable.
How ever the solution is very similar.
#{ Html.ViewData.TemplateInfo.HtmlFieldPrefix = "Contact"; }
#await Html.PartialAsync("_YourPartialName", Model.Contact)
after you can submit your model, it will bind again.
Hope that helps
You can add the HtmlFieldPrefix to the top of your partial view:
#{
ViewData.TemplateInfo.HtmlFieldPrefix = "Contact";
}
This is the same approach as that described by #cpoDesign but it means you can keep the prefix in your partial view if you need to do that.
You need to create an editor template for PreliminaryInformationViewModel to replace the partial view, then call with Html.EditorFor( m => m.PreliminaryInformation ). Reference this solution. Creating the template should be as simple as moving your partial view to the Views/Shared/EditorTemplates directory. Html.EditorFor(...) will automatically use this template based on the type you're passing in as the model (in this case, PreliminaryInformationViewModel)
I also ran into this problem. I will explain my solution using your code. I started with this:
#{
Html.RenderPartial("_PreliminaryInformation", Model.PreliminaryInformation);
}
The action corresponding to the http post was looking for the parent model. The http post was submitting the form correctly but there was no reference in the child partial to the parent partial. The submitted values from the child partial were ignored and the corresponding child property remained null.
I created an interface, IPreliminaryInfoCapable, which contained a definition for the child type, like so:
public interface IPreliminaryInfoCapable
{
PreliminaryInformationViewModel PreliminaryInformation { get; set; }
}
I made my parent model implement this interface. My partial view then uses the interface at the top as the model:
#model IPreliminaryInfoCapable
Finally, my parent view can use the following code to pass itself to the child partial:
#{
Html.RenderPartial("ChildPartial", Model);
}
Then the child partial can use the child object, like so:
#model IPreliminaryInfoCapable
...
#Html.LabelFor(m => m.PreliminaryInformation.ProviderName)
etc.
All of this properly fills the parent model upon http post to the corresponding action.
Quick Tip: when calling your EditorFor method, you can set the name of the template as a parameter of the Html.EditorFor method. Alternatively, naming conventions can be your friend; just make sure your editor template filename is exactly the same name as the model property type
i.e. model property type 'CustomerViewModel' => 'CustomerViewModel.cshtml' editor template.
Please make the below changes to your partial page. so it will come with your Parent model
//Parent Page
#{Html.RenderPartial("_PreliminaryInformation", Model.PreliminaryInformation);}
//Partial Page
#model Web.Models.Preliminary.PreliminaryInformationViewModel
#using (Html.BeginCollectionItem("PreliminaryInformation", item.RowId, true))
{
<div>
#Html.TextBoxFor(x => x.DateOfService })
</div>
}
For .net core 2 and mvc, use do like below:
#{
Html.ViewData.TemplateInfo.HtmlFieldPrefix = "Contact";
}
#await Html.PartialAsync("_YourPartialViewName", Model.Contact)

Why does ASP.NET MVC assumes that view will have matching input and output types?

ASP.NET MVC (or rather Html.Helpers and base page implementation) assumes that there will be one type for both rendering and posting (namely Model).
This is a violation of ISP, isn't it?
I am tempted to derive my Edit views (those that have different render-data, and post-data) from a custom EditPageBaseView<TViewModel, TFormData>.
The problem is I want my validation and post work against FormData instance (stored inside ViewModel), but MVC assumes that entire ViewModel will be POSTed back.
Is there an OOB way to facilitate that? (I didn't find one if there is).
Is it a bad idea (in concept) to have separate data types for different operations exposed by a service (a view in this case).
I tend to follow the CQRS model when constructing my view models. All rendering is done with ViewModel classes and all posting back is done with Command classes. Here's a contrived example. Let's say we have a View with a small form for creating users.
The ViewModel and Command classes looks like this:
public abstract class ViewModel {}
public abstract class Command: ViewModel
public class CreateUserViewModel : ViewModel
{
public string Username { get; set; }
public string Password { get; set; }
public string PasswordConfirm { get; set; }
}
public class CreateUserCommand : Command
{
public string Username { get; set; }
public string Password { get; set; }
public string PasswordConfirm { get; set; }
}
The UserController creates a CreateUserViewModel as the model for the Get request and expects a CreateUserCommand for the Post request:
public ActionResult CreateUser()
{
// this should be created by a factory of some sort that is injected in
var model = new CreateUserViewModel();
return View(model);
}
[HttpPost]
public ActionResult CreateUser(CreateUserCommand command)
{
// validate and then save the user, create new CreateUserViewModel and re-display the view if validation fails
}
Model binding takes care of ensuring that the properties of the Posted CreateUserCommand are populated properly, even though the Get View is bound to a CreateUserViewModel.
They don't have to match, but they do match by default.
If you don't want them to match, you can specify a different model in your Form or ActionLink:
Example of a Mismatch using Razor and C#:
Index.chtml:
#model FirstModel
<div>
#using (Html.BeginForm("Action", "ControllerName", new { ParameterName = new SecondModel { First = "First", Second = "Second" } }, FormMethod.Post)) {
<input type="submit" value="Submit Button" />
}
</div>
The Controller:
public class ControllerName : Controller {
public ActionResult Index() {
return View(new FirstModel());
}
public ActionResult Action(SecondModel ParameterName) {
return View() // Where to now?
}

Can I get a SelectList in my view model to render using EditorForModel?

I would like have a listbox of states render using the EditorForModel Html helper.
My view model:
public class MyViewModel
{
public MyewModel()
{
States = new SelectList(MyModel.RegionsToSelectList,"Value","Text");
}
[DataType(DataType.Text)]
public string City { get; set; }
[Display(Name = "States")]
public SelectList States { get; private set; }
}
In my view I have #Html.EditorForModel()
The City renders properly but the States do not render into any sort of list (dropdown or listbox)
If I use #Html.DropDownList("mylistname", Model.States) it renders properly.
I would really like to have it render in the ForModel process.
Can this be done?
You need to use the Html.DropdownListFor helper if you want to generate a drop down list. The fact that you have used SelectList as type to some of your properties doesn't mean that the default editor template will render a box. So you will have to write a custom editor template.
You may take a look at the following blog post to see how those default templates are implemented.