views:

458

answers:

3

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.

+2  A: 

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.

Mehrdad Afshari
As the question says, my problem is that whenever I create a server control, the form gets rendered, which I do not want.
erikkallen
This is not true for all controls. That's the issue with the specific control, not ASP.NET MVC.
Mehrdad Afshari
The control I tested with is a blank control (I created a Server Control project and I'm testing with the default ServerControl1). How do I have to modify it to remove the view state?
erikkallen
I tested it and it doesn't generate any form tags or anything else whatsoever at runtime. There is, however, an issue with VS design view which creates a <form> tag when you drag a control to designer surface. You can easily remove the form tag in HTML mode.
Mehrdad Afshari
A: 

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

Eduardo Molteni
Sorry, it's too simple. I want my users to be able to use the VS2008 designer.
erikkallen
A: 

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

Parsa