Alternatives to server controls in MVC

2019-08-26 14:17发布

What is the replacement for a server control in ASP.NET MVC? What I want to do is to create a declarative and imperative binding so I can write

<cc1:MyControl Header="Some Header" Content="Some Content" />

which would mean that an instance of the MyControl class will be created and possibly rendered to

<h1>Some Header</h1>
<p>Content</p>

I don't want any viewstate or postback crap, just the modularity. I also want these modules to be contained in a separate class library, so ViewUserControls will not do for me. Using a server controls in the normal way works, but it generates a form tag and a viewstate field, which I do not want if I can avoid it.

I have seen this question and this one about how to use server controls in ASP.NET MVC, but they do not provide enough answer.

Edit: I found the answer. When I added the user control using the designer, it automatically created a <form> which I missed. If I simply remove that tag, everything works perfectly.

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-26 14:34

You can still use all controls in ASP.NET MVC if they don't require rendering in a server form.

ascx files and @Register directives still work pretty well. The great new thing is Html.RenderPartial method that lets you pass a model object to a partial view (ascx) and have it render accordingly.

查看更多
手持菜刀,她持情操
3楼-- · 2019-08-26 14:45

Just adding one more possibility to Mehrdad answer, you can use extension methods to do a simple control like this:

<%= html.MyControl( "Some header", "Some content" ) %>


<Extension()> _
Public Function MyControl(ByVal htmlHelper As HtmlHelper, _
                         ByVal Header As String, _
                         ByVal Content As String) As String

Dim sb As New StringBuilder()
sb.AppendFormat("<h1>{0}</h1>", Header)
sb.AppendFormat("<p>{0}</p>", Content)
Return sb.ToString()
End Function

Or you can make a more complex control like this example: Create an ASP.NET MVC GridView Helper Method

查看更多
We Are One
4楼-- · 2019-08-26 14:45

Other than the controls which still work with ASP.Net MVC, you can use mvc controls.

UPDATE: This answer was for ASP.Net MVC 1.0 in 2009. It is outdated and irrelevant at this point.

查看更多
登录 后发表回答