开发者

ASP MVC dynamic fields in editor

开发者 https://www.devze.com 2022-12-30 08:55 出处:网络
I have a form which will include some optional questions that need to asked of the user. In my model it may look like:

I have a form which will include some optional questions that need to asked of the user. In my model it may look like:

public Dictionary<String, String> Questions { get; set; }

Where the key is the label and value is the text box. How can I create and populate the controls for this? I am new to ASP MVC, but it makes sense that something like this would be built in.

Is there a built in way to do this, or do I have to implement it myself? It seems like there should be a helper for it, since you don't really want to put this kind of code in the view.

I've tried

Html.EditorFor(model => model.Questions);

But it just sp开发者_JAVA技巧its out "[key, value]" to the view.


There are a couple of ways you could go here.

  1. You could write your own helper quite easily - maybe something like this:

    public static string Question(Dictionary question) { Html.Label(question.Key); Html.Textbox(question.Value); }

  2. Create a custom display template for Dictionary<string, string> (or, rather, wrap the dictionary in a Question type to avoid ambiguity) that outputs what you want.


Why not implement a Question class? Something like this I had in mind:

public class QuestionControl
{
      public int QuestionId{get;set;}
      public string Question{get;set;}
      public string Answer{get;set;}
      public virtual string GetHtml()
      {
           return string.Format("<label for=\"{0}\">{2}</label><br><input type=\"text\" name=\"{0}\" id=\"{0}\" value=\"{1}\">", QuestionId, Answer, Question);
      }
}  

Also, this way you can inherit and override GetHtml and have questions with checkboxes, radiobuttons etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消