Using ViewModel with a PartialView in ASP.NET MVC - asp.net-mvc

I'm attempting to use a PartialView with a ViewModel but I am getting the error
The model item passed into the dictionary is of type 'Regression', but this dictionary requires a model item of type 'RegressionVM'.
Controller:
public ActionResult _Regression(Regression regression)
{
var model = new ViewModels.RegressionVM(regression);
return PartialView(model);
}
Partial View
#model ViewModels.RegressionVM
<div>
<p>Correlation Coefficient : #Model.Regression.CorrelationCoefficient</p>
</div>
Main View (relevant part)
#Html.Partial("_Regression", SectorAnalysis.evReg)
I've checked that the object passed to the partial controller is not null and is of the correct type.
If in the controller I simply take in a type Regression and pass it to the PartialView that works fine but I get errors whenever I use a view model pattern.
Interestingly if I omit the viewmodel from the partial controller as below the error goes away (obviously I change the partial view to accept #model Regression) :
public ActionResult _Regression(Regression regression)
{
return PartialView(regression);
}
I'm using ASP.NET MVC 4

You need to change this
#Html.Partial("_Regression", SectorAnalysis.evReg)
to this
#Html.Action("_Regression", "ControllerName", SectorAnalysis.evReg)
Rationale:
Html.Partial does not call the controller action, it simply attempts to render the partial view with the model that you sent it. In your case, you are sending a model of type Regression to a partial view that is expecting a model type of ViewModels.RegressionVM. By calling Html.Action(), you are instructing the razor view engine to execute the action in your controller that takes a Regression type object and returns a ViewModels.RegressionVM to the partial view.

Related

Pass variables to a partial view in MVC

How can I send variables to my partial view?
And I don't mean like my model, but values seperate from that
So instead of #Html.Partial("~/Views/Test/_Partial.cshtml", Model)
It would be something like #Html.Partial("~/Views/Test/_Partial.cshtml", Variable = 2)
And then in my partial view I could just use it like
// html
#Variable
// html
You can make the model of your partial the type you want to pass to it:
#model int
In the parent view:
#Html.Partial("~/Views/Test/_Partial.cshtml", 2)
Then access it from the partial view as #Model.
Following are the available options to pass data from a Controller to View in ASP.NET MVC which would be appropriate in your case:
ViewBag
ViewData
TempData
If we want to maintain state between a Controller and corresponding View- ViewData and ViewBag are the available options but both of these options are limited to a single server call (meaning it’s value will be null if a redirect occurs). But if we need to maintain state from one Controller to another (redirect case), then TempData is the other available option which will be cleared once hit.
public ActionResult Index()
{
ViewBag.EmployeeName = “Tushar Gupta”;
return View();
}
View
<b>Employee Name:</b> #ViewBag.EmployeeName<br />

Model usage within View

I think I'm not clear with the #model that can be part of the view
For example
#model MyModel
Is it the input argument that I can populate and call the view with?
return View("MyView", MyModel);
Is it the output variable I can populate during the post of the view (for next control action)
[HttpPost]
public ActionResult SomePostAction(MyModel myModel) //(and in post action)
Is it both ??
3, it's both!
It is called model binding. A feature of ASP.NET which makes it trivial to bind a mode to a view. Hence the name 'view model', which those models are usually called.
Assigning a model to your view gives you a so-called strongly typed view, which fully exposes the power over the Razor syntax.
The model binder is capable of binding the values of every input field back to the model when posting the form, as long as the name attribute of the form matches the name of the property on the view model. Html helpers such as Html.EditorFor(m => m.SomeProperty) makes this a trivial task.
As Mystere Man mentions, it's also possible to do this without an actual model in your view. For instance, this works:
Html (I omitted the form tag and submit button):
<input type="text" name="SomeString" />
with this method in your controller:
[HttpPost]
public ActionResult SomeAction(string someString)
{
// ...
}
The #model declaration at the top of your view is related to the model object you passed to the View() method in your controller (option 1 in your question). The #model declaration is your way of telling the Razor view engine that the view is strongly typed. That means the C# compiler can double check any properties of your view accesses.
Suppose you had the following class
public class MyModel
{
public string Name { get; set; }
}
Without a strongly typed view you might have something like this in your view
<div>
Hello, #Model.Nmae
</div>
Notice that there's a typo in Name. ASP.Net has no idea what your model is so it has to use a dynamic object. You won't find that error until runtime. If you had delcared #model MyModel you would have an error at build time because MyModel doesn't have a Nmae property.
However, it's not uncommon to use the same model type as a parameter of the action. Imagine your page is an HTML form. In that case the model that your view is strongly typed to and the model that's passed to an MVC action could be the same.

Partial View Action does'nt populate model data

I have a partial view which contains some data from the Model to be displayed. i created an Action of this Partial View in which I return the Model ,I want t display Partial view in each View of my MVC project. but the Problem is that when i return the Model in each View Method Action then it returns the Model and display data but when i am not using to return the Model in each view and want to return the Model only in the Partial view Action then data Model data is not Populating on Partial view .
I want to Return the Model only in the Partial view Action .My code is
public PartialViewResult _FlyMenu()
{
Category cat = new Category();
var category1 =cat.CategoryName;
return PartialView(category1);
}
There isn't anything passed to the partial view action, so there isn't anything that action can pass to the partial view itself.
There should be an argument for the model in the redirect call, and a parameter in the action arguments to receive it.
Assuming your model is of type Category I think you'd need something like this:
public PartialViewResult _FlyResult(Category c)
{
// method body here
}

Can I create and set property of MVC3 partial view

Like Asp.Net applications where we create User control(ASCX), and declare some properties for that user control, which we can set from the parent page where we are using the user control, can we do the same thing in Partial View of MVC?
I want to create a partial view for Date picker in MVC, having its validation(enable/disable) property,a flag(display as timepicker or datepicker) and many other such customizable properties, based on which my partial view will behave accordingly.And use this partial view at different places in same page.
You can use RenderAction()
You can call a controller action and pass parameters in here. The Controller action will then return a PartialView (With a model or just ViewBag Values)
public ActionResult DatePicker(bool DoSomething)
{
ViewBag.Something = DoSomething;
return PartialView("DatePicker");
}
and you call this
#Html.RenderAction("DatePicker", "ControllerName", new {DoSomething = true})
Look at Template Editor. This is a sample with a DateTimePicker.
Than you can pass a Model to your partialView for further actions in relation to the model's data.
Create class DatePickerParam like this
public class DatePickerParam{
public boolean isEnabled{get;set;}
//... some other properties
}
call Partial
<%=Html.Partial("~/Views/Shared/MyDatePicker.ascx",new DatePickerParam(){ isEnabled=true})%>
your partial view model class is DatePickerParam

ASP.NET MVC and strongly-typed partialview

I'm loading a partial view with an AJAX call:
public ActionResult LoadServerForm()
{
//data stuff
ViewData["ApplicationID"] = appID.ToString();
ViewData["Servers"] = ServersList(appServerRep.Session, null, appServers);
return PartialView("Application_AddServer");
}
This works great, but I'm trying to get away from magic ViewData strings. I tried making the partial view inherit from the same ViewModel as the "hosting" page, but the Model object is null when I try to this in the partial view:
<%= Html.HiddenFor(model=>model.Application_Key, Model.Application_Key) %>
Is there a way to pass the main page ViewModel down into the AJAX-loaded PartialView or should I be looking for a different approach altogether?
When you return PartialView("Application_AddServer");, you have to pass the model:
return PartialView("Application_AddServer", model);
Since this is an AJAX request, it's a separate controller action invocation, and the new PartialView doesn't know about the model of the requesting page. You'll have to reconstruct it, either from whatever your original data source is or from data passed with the AJAX request.

Resources