如何在mvc 2中使用asp服务器控件,如文本框,按钮,检查列表框网格视图?

时间:2014-01-20 06:31:49

标签: c#

我只想在MVC 2中使用asp.net服务器控件来执行添加,更新删除搜索功能。

但我做不到。我也想在MVC 2中使用网格。

我用这个..

    HtmlInputCheckBox chk = new HtmlInputCheckBox();
    ArrayList list = GetAllControls(new ArrayList(), chk.GetType(), this);

    foreach (Control c in list)
    {
        if (c is HtmlInputCheckBox)
        {
            string name = ((HtmlInputCheckBox)c).ID;
            bool check = ((HtmlInputCheckBox)c).Checked;
            string value = ((HtmlInputCheckBox)c).Value;
            this.Label1.Text += "Name: " + name + "\nStatus: " + check.ToString() + "\nValue: " + value;
        }

    }

}      
public static ArrayList GetAllControls(ArrayList list, Type type, Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if (c.GetType() == type)
        {
            list.Add(c);

        }
        if (c.HasControls())
        {
            list = GetAllControls(list, type, c);
        }

    }

    return list;
}

但它不能正常工作.......我只想在这里使用服务器控件而不是html控件...

3 个答案:

答案 0 :(得分:2)

您似乎想要访问控制器视图中可用的控件。如果我的理解是正确的,那么我会说这不应该是使用MVC的正确方法。 在MVC中,您可以使用模型(或UxModel)强烈地键入您的视图,这只是一个POCO类,在表单POST上,您可以在操作方法中检索键入到属性-by end user中的值。之后,您可以在控制器中对模型进行所有操作。

如果您尝试访问控制器中的视图控件,那么这明显违反了“关注点分离”的概念。

答案 1 :(得分:1)

ASP.NET服务器控件适用于Web窗体,而不适用于MVC。 View&之间没有联系;控制器以外的模型。

在控制器中,您可以从不尝试以与Web窗体中相同的方式访问视图中呈现的控件,原因很简单,因为视图尚未呈现然而。此外,就像@Dannydust评论的那样,MVC应用程序没有任何视图状态,因此没有生命周期来维护在先前页面视图上呈现的控件。

您必须接受MVC应用程序的流程

  1. 请求来自
  2. 路由决定了该做什么
  3. 调用Controller / Action(希望如此)
    1. Controller构建模型
    2. Controller传递模型以查看
  4. 调用视图并呈现模型
  5. 一旦你点击 4 ,就不会回到控制器并尝试执行服务器逻辑。如果我猜测你想要实现的目标,那么在MVC中会是这样的:

    模型

    public class MyModel {
      public bool Value1 { get; set; }
      public bool Value2 { get; set; }
    }
    

    控制器

    public class MyController : Controller {
      public ActionResult Index() {
        return View(new MyModel());
      }
    
      [HttpPost]
      public ActionResult Save(MyModel model) {
        // The values of the model will now be updated from the view
      }
    }
    

    视图

    @model MyModel
    
    <h2>Welcome to the view</h2>
    @{ Html.BeginForm("Save"); }
    <ul>
      <li>Value1: @Html.CheckBoxFor(m => m.Value1)</li>
      <li>Value2: @Html.CheckBoxFor(m => m.Value2)</li>
    </ul>
    <button type="submit">Save it</button>
    @{ Html.EndForm(); }
    

    以上代码未经过任何方式测试,但我希望您了解它的工作原理:)

    问候!

答案 2 :(得分:0)

更好的是你可以使用HtmlGenericControl

HtmlGenericControl div = new HtmlGenericControl(“div”);