Solved

C# Razor beginform binding nested object in view and post it all back to controller

Posted on 2016-08-05
7
39 Views
Last Modified: 2016-08-26
I have a view model like this:
namespace MySystem.Models.View {
   public class ItemPage {
      public Item Item { get; set; }
      public int CurrentItemID { get; set; }
      public string ModalHeading { get; set; }
      public string SubmitButtonText { get; set; }
      /// <summary>
      /// This will be the color that we will use in the view, if set
      /// </summary>
      public System.Drawing.Color CssColorTwist { get; set; }
      public ItemPage() {
         //ItemEngine iEngine = new ItemEngine();
         //this.Item = iEngine.GetItem(CurrentItemID);
      }
      public ItemPage(Item item) {
         this.Item = item;
         this.CurrentItemID = Item.ItemID;
      }
      public ItemPage(Item item, string btnText, string modalHeading) {
         this.Item = item;
         ModalHeading = modalHeading;
         SubmitButtonText = btnText;
         this.CurrentItemID = Item.ItemID;
      }
      public ItemPage(Item item, string btnText, string modalHeading, System.Drawing.Color cssColor) {
         this.Item = item;
         ModalHeading = modalHeading;
         SubmitButtonText = btnText;
         CssColorTwist = cssColor;
         this.CurrentItemID = Item.ItemID;
      }
      public Color GetCssColorDarker(double factor) {
         if(CssColorTwist != null) {
            return CssColorTwist.GetColorDarker(factor);
         }
         return new Color();         
      }
      public Color GetCssColorLighter(double factor) {         
         if (CssColorTwist != null) {
            return CssColorTwist.GetColorLighter(factor);
         }
         return new Color();
      }
   }
}

Open in new window


I want to bind and set the nested item properties in the view like this:
<span class="display-form-item">@Html.DisplayNameFor(model => model.Item.Address):</span>
@Html.TextBoxFor(model => model.Item.Address, new { @id = "addressID-" + @Model.Item.ItemID, @class = "form-control", data_toggle = "tooltip", data_placement = "bottom", @title = "Skriv inn adresse" })
@Html.ValidationMessageFor(model => model.Item.Address, String.Empty, new { @class = "alert-danger" })

Open in new window


When posting to the controller, all the properties of the view model end up as null. If I remove the nested object Item from the view model and remove all bindings to that nested object in the view, then all works good, all other properties are set.

So the problem is, how to bind nested object properties in the Item object in the view and post back to the controller with the model and nested object and all?
0
Comment
Question by:itnifl
  • 4
  • 2
7 Comments
 
LVL 8

Assisted Solution

by:Prakash Samariya
Prakash Samariya earned 250 total points
ID: 41744063
Ideally, ViewModel with nested object works fine in MVC!  

You might missing some steps, please check in controller, when you get ItemPage object initialised, check for Item object as well if it is initialised or not!! If Item object is null, then in views, it end up.

If not works, please paste snapshot of error and controller code as well to look into that as well
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 250 total points
ID: 41744098
What does the name attribute of the textbox show in the rendered HTML?
0
 
LVL 2

Author Comment

by:itnifl
ID: 41744254
The controller is irrelevant here, but here it is:
      [Authorize(Roles = "Admin")]
      [HttpPost]
      public ActionResult SaveItemInItemPage(ItemPage item) {
         ItemEngine iEngine = new ItemEngine();
         iEngine.UpdateItem(item.Item);
         return Redirect(Request.UrlReferrer.AbsoluteUri);
      }

Open in new window

ItemPage shall already have been initialized when received by the controller method with the values input by the user in the view via the bindings there.

The whole view looks like this. Bare in mind that this is only a test under construction. I have squared the name with a red box in the picture.

View result
There is no error message. As stated in the question, all properties of the model end up as null when received by the controller (verified via debugging at runtime in Visual Studio) unless I remove the Item object bindings from the view and remove the Item object from the model. In short; it works, the properties are populated by the user input, as long as I don't use a nested object as a property (the Item object). But that is what I want to do.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 41744380
What is the answer to my question?
0
 
LVL 2

Author Comment

by:itnifl
ID: 41744446
Sorry, misunderstood you. Looks like this:
<div class="form-group custom-line-rowheight">
	<span class="display-form-item">Adresse:</span>
	<input class="form-control" data-placement="bottom" data-toggle="tooltip" id="addressID-1" name="Item.Address" title="Skriv inn adresse" type="text" value="">
	<span class="field-validation-valid alert-danger" data-valmsg-for="Item.Address" data-valmsg-replace="true"></span>
</div>

Open in new window


Or like this:

<div class="form-group">
	<span class="display-form-item">Beskrivelse:</span>
	<textarea class="form-control input-lg" cols="20" data-placement="bottom" data-toggle="tooltip" id="infoID-1" name="Item.Description" rows="2" title="Skriv beskrivelse">Dette er en flott hytte med fyrtårn!</textarea>
	<span class="field-validation-valid alert-danger" data-valmsg-for="Item.Description" data-valmsg-replace="true"></span>
</div>

Open in new window


So in these examples the names are:
  • Item.Address
  • Item.Description
0
 
LVL 2

Accepted Solution

by:
itnifl earned 0 total points
ID: 41764447
I ended up with writing a partialview that acted as editor for Item, then I used @Html.EditorFor(model => model.Item) to display the view. That worked.
0
 
LVL 2

Author Closing Comment

by:itnifl
ID: 41771435
Using EditorFor solved the problem.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SqlDataBase 7 46
How to call weather service by using asmx? 4 29
SQL Help 27 40
Help with preventing selection from a combobox 9 17
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now