1

I am creating Textbox control Dynamically as following, but on HttpPost it is not returning anything back. I am expecting the value of textbox to be accessible in Controller on HttpPost. Can anyone please suggest me how I can achieve this. Thanks

Models

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; }
}

Controller

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

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

View

<%@ 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>

UserControl

<%@ 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>
user1211185
  • 731
  • 3
  • 12
  • 27
  • Your creating controls with duplicate `name` (and invalid `id` attributes). Some options for dynamically adding objects [here](http://stackoverflow.com/questions/29161481/post-a-form-array-without-successful/29161796#29161796) and [here](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308). But in any case, you post parameter will only ever initialize a collection of `ControlViewModel` not `TextBoxViewModel` so `Html.TextBoxFor(x => x.Value)` will be ignored –  Apr 21 '15 at 13:32
  • @StephenMuecke thanks. Can you provide an example please. – user1211185 Apr 21 '15 at 13:43
  • I gave you 2 links in my previous comment –  Apr 21 '15 at 13:45

1 Answers1

-2

I think you should use FindControl()..

Take a look on Getting values from dynamic textboxes

pregoli
  • 100
  • 7