【问题标题】:How to get the value of dynamically created textbox on HttpPost如何在 HttpPost 上获取动态创建的文本框的值
【发布时间】:2023-04-04 03:05:01
【问题描述】:

我正在创建Textbox 动态控制如下,但在HttpPost 上它没有返回任何东西。我希望可以在HttpPost 上的控制器中访问文本框的值。谁能建议我如何实现这一目标。谢谢

模型

public class MyViewModel
{
    public ControlViewModel[] Controls { get; set; }
}

public abstract class ControlViewModel
{
    public abstract string Type { get; }
    public bool Visible { get; set; }
    public string Label { get; set; }
    public string Name { get; set; }
}

public class TextBoxViewModel : ControlViewModel
{
    public override string Type
    {
        get { return "textbox"; }
    }
    public string Value { get; set; }
}

控制器

public ActionResult Index(Guid? id)
{
    return Results(id);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    // Logic here
}

查看

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Site.master"
 Inherits="System.Web.Mvc.ViewPage<MySite.Model.ViewModels.MyViewModel>" %>

<div>
    <% using (Html.BeginForm("Index", "MyController", FormMethod.Post, null))
    { %>
        <% for (int i = 0; i < Model.Controls.Length; i++)
           { %>
               <%Html.RenderPartial("TextboxControl", (TextBoxViewModel)Model.Controls[i]); %>             
        <% } %>
        <input type="submit" value="Submit" class="btn btn-primary"/>       
    <% } %>
   </div>

用户控制

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MySite.Model.ViewModels.TextBoxViewModel>" %>
<div>
     <%
           var controlType = Model.Type;
           var controlName = Model.Name;               
     %>
     <%= Html.TextBoxFor(x => x.Value, new { id = controlName, type = controlType, @class = "input-medium" })%>
</div>

【问题讨论】:

  • 您创建的控件具有重复的name(和无效的id 属性)。动态添加对象herehere 的一些选项。但无论如何,您发布的参数只会初始化ControlViewModel 而不是TextBoxViewModel 的集合,因此Html.TextBoxFor(x =&gt; x.Value) 将被忽略
  • @StephenMuecke 谢谢。可以举个例子吗?
  • 我在之前的评论中给了你 2 个链接

标签: c# asp.net asp.net-mvc asp.net-mvc-3 c#-4.0


【解决方案1】:

我认为你应该使用 FindControl()..

看看Getting values from dynamic textboxes

【讨论】:

  • 这是 MVC。控制器不知道页面控件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 2022-01-20
相关资源
最近更新 更多