1

I have looked at most of the available help in SO and google related to this but I'm not sure what I'm doing wrong.

I have Model with some properties, and one of the properties is a list of another complex object. I'm not able to bind this list!

Pleas help!

Here is my Model classes related:

public class PrivacyModel
{
        public int RatingId { get; set; }
        public List<RatingPoint> RatingPoints { get; set; }
}

public class RatingPoint
{
        public int RatingItemId { get; set; }
        public string RatingValue { get; set; }
}

Here is my code:

 [HttpPost]
 public ActionResult Index(PrivacyModel model)
 {
     .... my business logic....
 }

My view looks like this:

    @using (Html.BeginForm("Index", "Privacy"))
        {

            <input type="hidden" name="RatingId" value="@Model.RatingId" />

            for (var i = 0; i < Model.RatingPoints.Count; i++)
            {

                var ratingPoint = Model.RatingPoints[i];

                <input type="hidden" name="PrivacyModel.RatingPoints[@i].RatingItemId" value="@ratingPoint.RatingItemId" />

                <input type="hidden" name="PrivacyModel.RatingPoints[@i].RatingValue" @("id=RatingPoints" + ratingPoint.RatingItemId) value="@ratingPoint.RatingValue" />
            }
       <input class="btn" type="submit" value="Submit" />
     }

Please don't mind the value and id fields, they are being updated by jQuery somewhere in my page correctly.

This got me a null list of RatingPoints in my action

I have tried also without the prefix PrivacyModel in PrivacyModel.RatingPoints[@i]., but this got me an empty list of RatingPoints in my action

I have also tried using an Index like in the suggested solution here for non-sequential items

2
  • Always use the strongly typed HtmlHelper methods to generate your html. - @Html.HiddenFor(m => m.RatingPoints[i].RatingItemId) - now inspect the correct name attribute it generates with yours :) Commented Apr 14, 2016 at 12:42
  • I will try, as also suggested by Ehsans answer below Commented Apr 14, 2016 at 13:07

1 Answer 1

3

You are making it complex yourself, you can just use HiddenFor() helper for this:

for (var i = 0; i < Model.RatingPoints.Count; i++)
{


  @Html.HiddenFor(x=> Model.RatingPoints[i].RatingItemId)
  @Html.HiddenFor(x=> Model.RatingPoints[i].RatingValue,new { id= "RatingPoints"+Model.RatingPoints[i].RatingItemId})      

 }

and this will render the same html, and values will be correctly binded in Model at post.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.