开发者

asp.net mvc 3 and dynamic view generation

I am working on implementing a custom user profile screen.

This is pretty much a typical profile screen for a user that you would find on most any web site that has some sort of membership element.

In my case, since the screen is part of a market research SAS product, the data points that would be displayed on the profile will vary by market research product. The moderator of the product would specify what data points need to be capture by providing the following informati开发者_StackOverflow中文版on:

Field name, display name, field type (text, numeric, radiobutton, checkbox, etc), required …

I’m stuck trying to figure out how to dynamically generate the MVC view to reflect the list of data points requested. I would like to use the as much of the MVC framework as possible without having to write my own helper to generate the html. I would also like to use the unobtrusive validation if at all possible.

I’m gotten myself confused as to what the best approach is at this point.

Do I try to use:

  • a custom model binder
  • code generation to generate a model class at runtime and bind it to the view
  • just generate the html

Is there some other approach that might make more sense (jQuery templates), editor templates, a series of partial views?


If you are unsure what is going to be submitted to the server for any given action, you can have that action take in a parameter of type FormCollection and then iterate through the fields. At that point you would probably want to handle each type of field case by case, using the name of that field as the key.

In order to send the items to the view, just wrap the data for each field in a class, something like:

public class DataPoint
{
    public string FieldName { get; set; }
    public string DisplayName { get; set; }
    public object Value { get; set; }
}

Then have your view iterate your DataPoints. The EditorFor() method will handle the type checking of Value to produce the correct input type. The only other tricky part here is to get the FieldName as the name of that input.

Building classes as runtime is going to be an excessive amount of work for something that isn't overly complicated in the first place. A custom ModelBinder wont help you unless you know the model you are binding to, which is the root of your problem.


Can you go ahead and lay out your view with all fields bracketed by named divs then in your render Action have the Controller add a class "hidden" defined as

   .hidden
   {
      display:none;
   }

to each of the divs containing a field you do not need?

The other choice is write an HTML extension method that builds the view dynamically. You could create partial views for each control type and one by one the extension inserts them into HtmlString that gets rendered.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜