Solved

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

Posted on 2016-08-05
7
46 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 10

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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Suggested Solutions

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

726 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