1

我正在为我正在处理的项目制作测试页面,到目前为止我已经取得了预期的进展,但我正在尝试从传递给视图的 List 模型创建 TextBoxes,但是,它似乎只是忽略我尝试过的任何东西。

<form id="form1" runat="server">
    <input id="btnsubmit" type="submit" name="Submit" onclick="Submit" />
    <div id="divControls">
     <% foreach (TextBox control in (this.Model as List<TextBox>))
        {
            Html.Label("lblLabel", control.Text);
            Html.TextBox(control.ID, control.Text, new { id = control.ID, style = "width:50", name = "txt" + control.ID });
        } %>
    </div>
</form>

返回时控制器中的列表不为空。我不知道问题可能是什么。如果我抛出一个

某物

在 for 循环中,它执行了适当的次数,那么为什么不创建标签或文本框呢?起初我以为是我将它们添加到表单中,但我删除了表单标签,它仍然无法正常工作,所以我真的不知道,任何帮助将不胜感激。我对 MVC 比较陌生。

[HttpPost]
        public ActionResult Index(FormCollection form)
        {
            List<TextBox> controls = new List<TextBox>();
            foreach (String Key in form.Keys)
            {
                if (Key.Contains("txt"))
                {
                    TextBox textBox = new TextBox();
                    textBox.ID = Key;
                    textBox.Text = form.GetValues(Key)[0];
                    controls.Add(textBox);
                }
            }
            return View("Index", controls);
        }

这是我的动作包,它很有帮助。另外,我还不够清楚,我在运行时使用 JQuery 向表单添加控件,然后该 Action 将成为提交的一部分,因此它必须将文本框发送回视图,以便它们不会被删除。就像我说的那样,我对整个 MVC 和异步事物都是新手,所以如果有更好的方法可以做到这一点,我们将不胜感激。

4

2 回答 2

1

你没有打印 html

<% foreach (TextBox control in (this.Model as List<TextBox>))
        {%>
            <%=Html.Label("lblLabel", control.Text)%>
            <%=Html.TextBox(control.ID, control.Text, new { id = control.ID, style = "width:50", name = "txt" + control.ID })%>
<%        } %>

您的代码正在循环通过控件,并且Html.whaterever正在返回一个字符串,但您没有对它做任何事情,只是将其丢弃。

您也不需要返回整个TextBox对象。这可能是低效的。只需返回一个struct或一个class包含您的数据

于 2012-10-24T15:58:14.370 回答
0

Html.Label返回一个包含<label>标签的字符串。
您正在丢弃该字符串。

您需要通过 write 将其写入页面<%= Html.Whatever() %>

于 2012-10-24T15:58:02.987 回答