MVC Passing ViewModel to #Html.Partial - asp.net-mvc

Passing ViewModel to #Html.Partial
Have two ViewModels
public class RegisterVM
{
... some properties
public AddressVM AddressInformation { get; set; } //viewmodel
}
public class AddressVM {
public string Street1 { get; set; }
public string Street2 { get; set; }
public string PostalCode { get; set; }
}
When loading main view using VM:
#model ViewModels.RegisterVM
All field load. But When I add Partial View and pass viewmodel
#Html.Partial("_AddressDetails", Model.AddressInformation)
It fails
Error: Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Why does it fail?
The partial View _AddressDetails is expecting a
#model ViewModels.AddressVM
Update
Based on changes from Prashant,
When submitting the information The Address information is NULL.
In The controller:
[HttpPost]
public ActionResult Register(RegisterVM vm){
...
//when viewing vm.AddressInformation.Street1 is null. and there is a value
//Is there a different way of retrieving the values from partial view?
}
Thanks for reading.

The error is generated because property AddressInformation is null, and you need to initailize it in a parameterless constructor or in the controller before you pass it to the view, for example
public class RegisterVM
{
public RegisterVM() // default constructor
{
AddressInformation = new AddressVM();
}
public AddressVM AddressInformation { get; set; }
....
}
However you usage means that the controls generated will be
<input name="Street1" .../>
whereas they need to be
<input name="AddressInformation.Street1" .../>
in order to bind to your model. You can either make your partial an EditorTemplate (/Views/Shared/EditorTemplates/AddressVM.cshtml) and use in the main view as
#Html.EditorFor(m => m.AddressInformation)
or pass the prefix to the partial as additional ViewData
#Html.Partial("_AddressDetails", Model.AddressInformation, new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "AddressInformation" }})

This is working for me. You just need to instantiate your VM, attach it and send it to the view.
Page Action
public ActionResult Page(){
RegisterVM vm = new RegisterVM();
vm.AddressInformation = new AddressVM();
return View(vm);
}
Page.cshtml
#model Project.Web.Models.RegisterVM
<!-- loading partial view -->
#Html.Partial("_AddressDetails",Model.AddressInformation)
Partial View File
<input type="text" name="name" value=" " />

I am not having more info about code but as per mention details, can you try this
public ActionResult Register(){ return View(register); }
i know you may tried this but try to assigned explict value. as this is basic MVC implementation. if it not work out then you need to provide more code details.
hope this help.

in Register get Method must instatiate your viewModel because in view, call other partial with viewModel members(proprties);
public ActionResult Register(){
RegisterVM vm = new RegisterVM();
return View(vm);
}

Related

How to persist an object in view model on post back [duplicate]

I have a ViewModel that has a complex object as one of its members. The complex object has 4 properties (all strings). I'm trying to create a re-usable partial view where I can pass in the complex object and have it generate the html with html helpers for its properties. That's all working great. However, when I submit the form, the model binder isn't mapping the values back to the ViewModel's member so I don't get anything back on the server side. How can I read the values a user types into the html helpers for the complex object.
ViewModel
public class MyViewModel
{
public string SomeProperty { get; set; }
public MyComplexModel ComplexModel { get; set; }
}
MyComplexModel
public class MyComplexModel
{
public int id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
....
}
Controller
public class MyController : Controller
{
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
model.ComplexModel = new MyComplexModel();
model.ComplexModel.id = 15;
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// model here never has my nested model populated in the partial view
return View(model);
}
}
View
#using(Html.BeginForm("Index", "MyController", FormMethod.Post))
{
....
#Html.Partial("MyPartialView", Model.ComplexModel)
}
Partial View
#model my.path.to.namespace.MyComplexModel
#Html.TextBoxFor(m => m.Name)
...
how can I bind this data on form submission so that the parent model contains the data entered on the web form from the partial view?
thanks
EDIT: I've figured out that I need to prepend "ComplexModel." to all of my control's names in the partial view (textboxes) so that it maps to the nested object, but I can't pass the ViewModel type to the partial view to get that extra layer because it needs to be generic to accept several ViewModel types. I could just rewrite the name attribute with javascript, but that seems overly ghetto to me. How else can I do this?
EDIT 2: I can statically set the name attribute with new { Name="ComplexModel.Name" } so I think I'm in business unless someone has a better method?
You can pass the prefix to the partial using
#Html.Partial("MyPartialView", Model.ComplexModel,
new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "ComplexModel" }})
which will perpend the prefix to you controls name attribute so that <input name="Name" ../> will become <input name="ComplexModel.Name" ../> and correctly bind to typeof MyViewModel on post back
Edit
To make it a little easier, you can encapsulate this in a html helper
public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName)
{
string name = ExpressionHelper.GetExpressionText(expression);
object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
var viewData = new ViewDataDictionary(helper.ViewData)
{
TemplateInfo = new System.Web.Mvc.TemplateInfo
{
HtmlFieldPrefix = string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix) ?
name : $"{helper.ViewData.TemplateInfo.HtmlFieldPrefix}.{name}"
}
};
return helper.Partial(partialViewName, model, viewData);
}
and use it as
#Html.PartialFor(m => m.ComplexModel, "MyPartialView")
If you use tag helpers, the partial tag helper accepts a for attribute, which does what you expect.
<partial name="MyPartialView" for="ComplexModel" />
Using the for attribute, rather than the typical model attribute, will cause all of the form fields within the partial to be named with the ComplexModel. prefix.
You can try passing the ViewModel to the partial.
#model my.path.to.namespace.MyViewModel
#Html.TextBoxFor(m => m.ComplexModel.Name)
Edit
You can create a base model and push the complex model in there and pass the based model to the partial.
public class MyViewModel :BaseModel
{
public string SomeProperty { get; set; }
}
public class MyViewModel2 :BaseModel
{
public string SomeProperty2 { get; set; }
}
public class BaseModel
{
public MyComplexModel ComplexModel { get; set; }
}
public class MyComplexModel
{
public int id { get; set; }
public string Name { get; set; }
...
}
Then your partial will be like below :
#model my.path.to.namespace.BaseModel
#Html.TextBoxFor(m => m.ComplexModel.Name)
If this is not an acceptable solution, you may have to think in terms of overriding the model binder. You can read about that here.
I came across the same situation and with the help of such informative posts changed my partial code to have prefix on generated in input elements generated by partial view
I have used Html.partial helper giving partialview name and object of ModelType and an instance of ViewDataDictionary object with Html Field Prefix to constructor of Html.partial.
This results in GET request of "xyz url" of "Main view" and rendering partial view inside it with input elements generated with prefix e.g. earlier Name="Title" now becomes Name="MySubType.Title" in respective HTML element and same for rest of the form input elements.
The problem occurred when POST request is made to "xyz url", expecting the Form which is filled in gets saved in to my database. But the MVC Modelbinder didn't bind my POSTed model data with form values filled in and also ModelState is also lost. The model in viewdata was also coming to null.
Finally I tried to update model data in Posted form using TryUppdateModel method which takes model instance and html prefix which was passed earlier to partial view,and can see now model is bound with values and model state is also present.
Please let me know if this approach is fine or bit diversified!

Object reference not set when passing TextAreaFor to controller

The app is designed to allow the user to enter a an IP address for a local machine and and it will then return the HDD information for that machine. It starts out with a default value already in the TextAreaFor box and performs the query for that value. This part works with no problem. But when a user tries to enter in their own value and hit the Refresh button, it keeps coming up with the error Object reference not set to an instance of an object.
I'm not sure why this is happening. It seems to me that clicking the button submits a POST action, which should kick off the second method in the controller. The current model is then passed to the controller with the values in the TextAreaFor attached and the mainCode() method is run on the new values.
Edit: According to What is a NullReferenceException, and how do I fix it? I am pretty sure that I am returning an empty model from my controller. I just don't see how. The form field should be sending the controller everything contained in TextAreaFor so the model should not be empty.
Edit2: I did some testing and the model is getting returned alright, but the values from TextAreaFor are not. When the mainCode() tries to do some logic to startDrives.startingDrives, it can't because that variable is empty for some reason.
Model:
namespace RelengAdmin.Models
{
public class DriveInfo
{
public class DriveHolder
{
public string startingDrives {get; set;}
}
public DriveHolder startDrives = new DriveHolder();
public void mainCode()
{
/****Code to return the HDD size omitted****/
}
}
}
View:
#using (Html.BeginForm())
{
<input type="submit" value="Refresh" />
#Html.TextAreaFor(model => model.startDrives.startingDrives, new {#class = "HDDTextBox"})
}
Controller:
namespace RelengAdmin.Controllers
{
public class HDDCheckerController : Controller
{
[HttpGet]
public ActionResult Index()
{
DriveInfo myDrive = new DriveInfo();
myDrive.startDrives.startingDrives = "148.136.148.53"
myDrive.mainCode();
return View(myDrive);
}
[HttpPost]
public ActionResult Index(DriveInfo model)
{
model.mainCode();
return View(model);
}
}
}
The issue is that your model's startDrives property is not actually declared as a property with getters and setters, so the model binder won't bind to it. I was able to duplicate the issue locally, and solve it by declaring the startDrives as a property and initializing it in the constructor.
public class DriveInfo
{
public class DriveHolder
{
public string startingDrives { get; set; }
}
public DriveHolder startDrives { get; set; }
public DriveInfo()
{
startDrives = new DriveHolder();
}
public void mainCode()
{
/****Code to return the HDD size omitted****/
}
}
Your question is a bit unclear of where the model is actually null.. but I would assume that when you hit your button, it goes to the correct action, but there is nothing in model because you haven't passed any specific values..
so try this:
CSHTML
#using (Html.BeginForm())
{
<input type="submit" value="Refresh" />
#Html.TextArea("startingDrive", "148.136.148.53", new {#class = "HDDTextBox"})
}
Controller
[HttpPost]
public ActionResult Index(string startingDrive)
{
DriveInfo searchThisDrive = new DriveInfo();
searchThisDrive.startDrives.startingDrives = startingDrive;
searchThisDrive.mainCode();
return View(searchThisDrive);
}
Let me know if this helps!

Bind model property collections

My scenario is much complicated so i simplified it with the example below. The main problem is binding collection properties of a model, specifying the path of the property like Html.TextBox("List[0].Name") and not the Html.TextBoxFor(t => t.List[0].Name). So, for the current view i will only know some of the metadata of the model so i will have to construct it this way. Here is the scenario :
Model
public class ModelTest
{
public int Id {get;set;}
public List<Foo> Collection {get;set;}
}
public class Foo
{
public string Value1 {get;set;}
public string Value2 {get;set;}
}
Controller
public class TestController: Controller
{
[HttpGet]
public ActionResult Test()
{
var model = new ModelTest()
{
Id = 455,
Collection = new List<Foo>()
{
new Foo(){ Value1 = "sagasga", Value2 = "Beul"},
new Foo(){ Value1 = "dgdsgds", Value2 = "fhfhd" }
}
};
return View(model);
}
[HttpPost]
public ActionResult Test( ModelTest model)
{
//....
return View();
}
View:
#using (Html.BeginForm())
{
#Html.TextBox("Id")
#Html.TextBox("Collection[0].Value1")
#Html.TextBox("Collection[0].Value2")
<input type="submit" value="Add" />
}
For the code above i get empty textboxes for the collection values. However, when the page is submited i get the model built correct in the Post method.
Many thanks,
Alex
This is the way to name you input fields when you wanna post a collection to your controller. However, you have to specify the initial value yourself. Your code is currently just creating textbox with the name property set to Collection[0].Value1. You still need to specify the input this way,
#Html.TextBox("Collection[0].Value1", Model.Collection.FirstOrDefault().Value1)
#Html.TextBox("Collection[0].Value2", Model.Collection.FirstOrDefault().Value2)

Asp.Net MVC3 - Complex class not being passed as null on [HttpPost] method

its me... yet again!
Ive got these class,
public class PrankTargetArgumentViewModel
{
public PrankTarget Target { get; set; }
public PrankDefinition Prank { get; set; }
public List<PrankArgument> Arguments { get; set; }
}
public class PrankArgument
{
public string Name { get; set; }
public string Value { get; set; }
}
and what I'm doing is - if this current ParkDefinition needs arguments them im doing an ActionRedirect on the save to another Action which should handle the gathering of the Arguments
My Action result is like this..
public ActionResult PrankArguments()
{
PrankInstance currentInstance = SessionContext.CurrentPrankInstance;
if (currentInstance == null)
throw new ArgumentNullException("currentInstance");
PrankTargetArgumentViewModel model = new PrankTargetArgumentViewModel();
model.Prank = currentInstance.Prank;
model.Target = currentInstance.Target;
string[] args = model.Prank.Arguments.Split('|');
model.Arguments = new List<PrankArgument>();
foreach (string s in args)
{
model.Arguments.Add(new PrankArgument { Name = s, Value = s });
}
return View(model);
}
my http post method is just an empty method with the parameter of PrankTargetArgumentViewModel
[HttpPost]
public ActionResult PrankArguments(PrankTargetArgumentViewModel model)
{
return View();
}
My HTML is like this..
#using (Html.BeginForm())
{
#Html.EditorFor(x => Model)
<p>
<input type="submit" value="Create" />
</p>
}
So my problem is this, on the PrankArguments(PrankTargetArgumentViewModel model) post back action, the model param is always null.. I've filled the object with values on the load so I guessed they would be there on the post back with the new arguments that I added.
so the flow goes like this.
Create Prank
If prank needs arguments then load ActionResult PrankArguments()
Add extra arguments to an already poplulated object.
save, Call ActionResult PrankArguments(PrankTargetArgumentViewModel model)
-- this is where the problem is, the model parameter is passed back as null.
Ive had this problem quite a few times and always just given up but im not going to let that happen this time!
any help would be great! cheers, Ste!
Ps. If you need anymore of my code just let me know.
EDIT - Removed view bag debug properties!
I think if I understand you correctly if your view is strongly typed to PrankTargetArgumentViewModel then all you have to do to retrieve the values is:
[HttpPost]
public ActionResult PrankArguments()
{
var pta = new PrankTargetArgumentViewModel();
TryUpdateModel(pta);
}
After reviewing my own code - I noticed that I didn't need the entire PrankTargetArgumentViewModel and a simple List of Arguments would have been fine.
I alterd my PrankArguments view to take an IEnumerable and used;
#using (Html.BeginForm())
{
#Html.EditorForModel()
<p>
<input type="submit" value="Finish" />
</p>
}
then had my post back method signature like this
[HttpPost]
public ActionResult PrankArguments(IEnumerable<PrankArgument> arguments)
which worked exactly how I wanted.
Thanks for all the suggestions guys.

ViewModel with List<BaseClass> and editor templates

I have a view that lists tables being added to a floor plan. Tables derive from TableInputModel to allow for RectangleTableInputModel, CircleTableInputModel, etc
The ViewModel has a list of TableInputModel which are all one of the derived types.
I have a partial view for each of the derived types and given a List of mixed derived types the framework knows how to render them.
However, on submitting the form the type information is lost. I have tried with a custom model binder but because the type info is lost when it's being submitted, it wont work...
Has anyone tried this before?
Assuming you have the following models:
public abstract class TableInputModel
{
}
public class RectangleTableInputModel : TableInputModel
{
public string Foo { get; set; }
}
public class CircleTableInputModel : TableInputModel
{
public string Bar { get; set; }
}
And the following controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new TableInputModel[]
{
new RectangleTableInputModel(),
new CircleTableInputModel()
};
return View(model);
}
[HttpPost]
public ActionResult Index(TableInputModel[] model)
{
return View(model);
}
}
Now you could write views.
Main view Index.cshtml:
#model TableInputModel[]
#using (Html.BeginForm())
{
#Html.EditorForModel()
<input type="submit" value="OK" />
}
and the corresponding editor templates.
~/Views/Home/EditorTemplates/RectangleTableInputModel.cshtml:
#model RectangleTableInputModel
<h3>Rectangle</h3>
#Html.Hidden("ModelType", Model.GetType())
#Html.EditorFor(x => x.Foo)
~/Views/Home/EditorTemplates/CircleTableInputModel.cshtml:
#model CircleTableInputModel
<h3>Circle</h3>
#Html.Hidden("ModelType", Model.GetType())
#Html.EditorFor(x => x.Bar)
and final missing peace of the puzzle is the custom model binder for the TableInputModel type which will use the posted hidden field value to fetch the type and instantiate the proper implementation:
public class TableInputModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ModelType");
var type = Type.GetType(
(string)typeValue.ConvertTo(typeof(string)),
true
);
var model = Activator.CreateInstance(type);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
return model;
}
}
which will be registered in Application_Start:
ModelBinders.Binders.Add(typeof(TableInputModel), new TableInputModelBinder());
and that's pretty much all. Now inside the Index Post action the model array will be properly initialzed with correct types.
There was "Derived Type Model Binder" in mvccontrib. But, unfortunately, there is no such binder in mvccontrib version 3

Resources