0
votes

I have a model of question list which of type BOOL, STRING and OBJECT. whenever i select any response it has to bind the value to the model and while submitting the form it has to post the value.

Model.cs

public enum QuestionType 
{
    bool,
    list,
    YesorNo
}

public class Question
{

        public string Id{ get; set; } 

        public QuestionType Type{ get; set; }

        public object ResponseValue{ get; set; }

        public List<Option> Option { get; set; }

}

The List option will have the list the options when the question type is list. Below is the Option model

public class Option
{

     public int Id{ get; set; }

     public string name{ get; set; }

     public bool selected{ get; set; }
}

so whenever iam giving the response for the question which is of

  • BOOL type then the value should be binded as True or False to the ResponseValue
  • LIST type then it has to get all the selected options along with the Id and name and bind it to ResponseValue as object
  • YesorNo then the value should be binded as Yes, NO or NA to the ResponseValue

Iam using c# razor view for model binding

@Html.CheckBoxFor(m => Model.ResponseValue, new { @class = "form-control" })

The above code throws error because of its datatype object but the checkboxfor accepts only bool data type.

Please suggest how make the ResponseValue to accept all the data type(bool, string and object)

1

1 Answers

0
votes

It would probably be better if you could come up with a design that does not make use of object, but if there is no other way, you might get it to work using something like the following:

Cast the variable to the corresponding type:

@{
    bool? responseValueBool = Model.ResponseValue as bool?;
}

Use the new variable in the call of the HTML Helper:

@if (responseValueBool.HasValue)
{
    var ResponseValue = responseValueBool.Value;
    @Html.CheckBoxFor(m => ResponseValue, new {@class = "form-control"});
}

Edit: To include the index in the element's name, you could put the ResponseValues into a list, so that you are able to pass the element as expected in the form of m => ResponseValue[index], as shown in the docs, e.g.:

var ResponseValue = new List<bool> {responseValueBool.Value};
@Html.CheckBoxFor(m => ResponseValue[0], new {@class = "form-control", name="ResponseValue[1]"});

You would need to take care of using continuous indexes though. Note that you are not forced to use the HTML Helper and could also create the HTML elements yourself to avoid that kind of workarounds.