Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top