Home > Blockchain >  MVC form data cant bind to the model
MVC form data cant bind to the model

Time:11-03

I have a MVC form where I am posting this data from JS over to this controller. I cant get this data to bind to the model. The current model is looking for the hidden field to be QuestionType[int] but I am not sure how to do that ant help would be great

html

<input data-val="true" data-val-required="The Char field is required." id="item_QuestionType_0_" name="item.QuestionType[0]" type="hidden" value="L">

view

@model List<MeetingPolling>
     int idx = 0;
     foreach (var item in Model)
            {
                <div >
                    <div >
                        @Html.HiddenFor(m => Model[idx].QuestionType)
                        @Html.HiddenFor(x => item.QuestionType, new { @id = string.Format("hfQuestionType{0}", item.labelControl), @name = string.Format("hfQuestionType{0}", item.labelControl), Value = item.QuestionType })
                     </div>
                </div>
                idx  ;
             }
          

current serialize data

item.QuestionType=LongAnswerText&1=sssssssssssssssssssssss&item.QuestionType=MultipleChoice&16=75

what model is looking for to be able to bind

QuestionType[0]=LongAnswerText&textboxfor_1=456456456456456456&QuestionType[1]=MultipleChoice&radioList_16=75

Model

public class PollingResponseFormViewModel
{
    public List<string> QuestionType { get; set; }
}

CodePudding user response:

You can't use a single Html.HiddenFor() field for a List<String> - you need to render those hidden inputs this way:

@for( Int32 i = 0; i < this.Model.QuestionType.Count; i   ) {
    @Html.HiddenFor( m => m.QuestionType[i] )
}

You must use for, not foreach( var foo in this.Model.QuestionType ) because the Expression<> passed into HiddenFor needs the int indexer for the List<T> property.


Also, change your view-model so QuestionType is a pre-initialized, get-only property, as otherwise it will be null by default and mess with everything:

public class PollingResponseFormViewModel
{
    public List<string> QuestionType { get; } = new List<String>();
}
  • Related