create dynamic controls with ASP.NET MVC

♀尐吖头ヾ 提交于 2019-12-21 06:51:11

问题


In my current application we create controls dynamically inside panel based on database value. Like, Type controls, Style, width, etc. Is it possible to do something like this using ASP.NET MVC?

Thanks, Alps


回答1:


ASP.Net MVC doesn't use server controls like ASP.Net webforms does.

What you're talking about is definitely possible, but MVC gets you down to the HTML level, rather than abstracting it into controls.

You'd likely want to be using partial views, or else looking at adding extension methods to the HTMLHelper class to help you generate dynamic content.


Here's a very simple example HtmlHelper extension method. It's simple, for sure, but you can see how it would be easy to expand it to output the dynamic html you'd need. This method takes an input value, and outputs no html if it's null, the value plus a "<br>" tag if "addBr" is set to true, or just the value if "addBr" is false.

public static string FieldOrEmpty(this HtmlHelper<T> helper, 
                                     object value, bool addBr) 
        {
            if (value == null)
            {
                return string.Empty;
            }
            else if (addBr)
            {
                return value.ToString() + "<br />";
            }
            else
            {
                return (value.ToString());
            }
        }
    }

You'd call this in your View with

<%= HtmlHelper.FieldOrEmpty(Model.Field1) %>


来源:https://stackoverflow.com/questions/1494790/create-dynamic-controls-with-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!