这两天在找怎么像webfrom里面那样操作用户控件,但发觉MVC用id好像访问不了用户控件.
那这个怎么解决呢?
我是这样解决这个问题的,如果大鸟们觉得还有更好的方法,可以交流一下.
好我们看个例子吧
先建一个MVC项目
在Views里面添加两个文件夹
Home、UserControl(放用户控件的文件夹)
Home里新建一个文件Index.aspx
UserControl里新建UserTextBox.ascx
在UserTextBox.ascx里面输入:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
您的信息:<%= Html.Encode(ViewData["Message"])%>
在Controllers里新建UserControlController.cs
输入
public ActionResult UserTextBox()
{
ViewData["Message"] = "我爱你~~~";
return PartialView();//注意这里不是View
}
打开Index.aspx文件输入
<%Html.RenderAction("UserTextBox","UserControl"); %>//第一个参数是action名字,第二个是文件夹
好这样就可以测试了
至于更复杂的东西,例如为控件添加属性,什么的,都差不多是这样做了…….