繁体   English   中英

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

[英]how to use asp server control in mvc 2,like text box,button,check list box grid view?

我只想在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控件...

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

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

ASP.NET Server控件适用于Web窗体,而不适用于MVC。 视图和控制器之间没有模型之间的链接。

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

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

  1. 请求进来
  2. 路由决定了该做什么
  3. 调用Controller / Action(希望如此)
    1. 控制器构建模型
    2. 控制器传递模型进行查看
  4. 调用View并呈现模型

一旦你达到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(); }

上面的代码没有以任何方式进行测试,但我希望你能了解它是如何工作的:)

问候!

更好的是你可以使用HtmlGenericControl

HtmlGenericControl div = new HtmlGenericControl(“div”);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM