ASP.NET MVC 中服务器控件的替代品是什么? 我想要做的是创建一个声明式和命令式绑定,这样我就可以编写
<cc1:MyControl Header="Some Header" Content="Some Content" />
这意味着将创建 MyControl 类的一个实例,并可能呈现给我,
<h1>Some Header</h1>
<p>Content</p>
我不需要任何视图状态或回发垃圾,只是模块化。 我还希望这些模块包含在单独的类库中,因此 ViewUserControls 不适合我。 以正常方式使用服务器控件是可行的,但它会生成一个表单标记和一个视图状态字段,如果我可以避免的话,我不想要它们。
我看过这个问题和这个关于如何在 ASP.NET MVC 中使用服务器控件,但他们没有提供足够的答案。
编辑:我找到了答案。 当我使用设计器添加用户控件时,它会自动创建一个
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)
如果不需要以服务器表单呈现,您仍然可以在 ASP.NET MVC 中使用所有控件。
ascx
文件和@Register
指令仍然工作得很好。 伟大的新事物是Html.RenderPartial
方法,它允许您将模型对象传递给分部视图 (ascx
) 并使其相应地呈现。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.只需在 Mehrdad 答案中添加一种可能性,您就可以使用扩展方法来执行如下所示的简单控件:
或者您可以制作一个更复杂的控件,如下例所示:创建 ASP.NET MVC GridView 帮助程序方法
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
除了仍然适用于 ASP.Net MVC 的控件之外,您还可以使用
mvc
控件。更新:此答案适用于 ASP。 Net MVC 1.0 于 2009 年发布。此时它已经过时且无关紧要。
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.