Search code examples
c#asp.net-mvccontrollerhtml-helper

How to take list of arguments with non static names anp.net.mvc-5 C#


I need to create some groups of RadioButtons in my survey. For them to be in separated groups I create name while going through foreach statement. The all have the same begining of the name. There is my code

@foreach (var answer in Model.PossibleAnswers)
{
    <div class="col-xs-2">
    @Html.RadioButtonMatrix(answer.IdAspect.ToString(), answer.IdAspect)
    </div>
}

And there is my method of custom Html Helper

public static HtmlString RadioButtonMatrix(this HtmlHelper helper, 
                                           string target, 
                                           int value)
{
    StringBuilder sb = new StringBuilder("SelectedValue.");
    sb.Append(target);

    string radioButton = 
      String.Format("<input name=\"" + sb + "\" type=\"radio\" value=\"{0}\"/>", value);

    return new HtmlString(radioButton);
}

So, is it possible to create a non static name of parametrs in method of controller? I found such attribute but suppose that's not that I need

[HttpPost]
public void GetAnswersMatrix([Bind(Prefix="SelectedValue")]List<String> selectedValues)
{
}

Thanks for your help!


Solution

  • I propose the following data structure to help you out a bit more:

    class QuizModel
    {
        public string HowMuchDoYouLikeCSharp {get;set;}
        public string HowMuchDoYouLikeCPlusPlus {get;set;}
    }
    
    public class QuizQuestion
    {
        public string Question { get; set; }
        public string QuestionModelProp {get;set;} //This must match a prop name in the QuizModel
        public List<string> PossibleAnswers { get; set; }
    
        public string generateHTML()
        {
            StringBuilder ret = new StringBuilder();
            ret.Append("<div>"+Question+"</div>");
            foreach (string answer in PossibleAnswers)
            {
                ret.Append(String.Format(@"<input name='{0}' type='radio' value='{1}'/>{1}<br/>", QuestionModelProp, answer));
            }
    
            return ret.ToString();
        }
    }
    
    [HttpPost]
    public ActionResult SubmitAction(QuizModel quizData)
    {      
        string HowMuchDoYouLikeCSharp = quizData.HowMuchDoYouLikeCSharp;
        string HowMuchDoYouLikeCPlusPlus = quizData.HowMuchDoYouLikeCPlusPlus;
    }
    

    You will have to modify a bit to suit your needs, but this should give you a good stepping off point, even included a rudimentary answer randomizer. To keep it form safe it may be best to treat the form values of answers and questions as hashes or guids rather than the literal strings, but that's an issue for a different question.

    Specifically note that since the question and the answers are in the same class, it is easy to create the radio group based on the question on the answer iteration.

    EDIT: Modified the code to be closer to your needs, also included a model as an example.