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.
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 isHtml.RenderPartial
method that lets you pass a model object to a partial view (ascx
) and have it render accordingly.Just adding one more possibility to Mehrdad answer, you can use extension methods to do a simple control like this:
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.