ASP.NET MVC: создание элементов управления динамически - PullRequest
3 голосов
/ 10 августа 2009

Это класс построителя элементов управления ...

public class ControlBuilder
{
    /// <summary>
    /// Html Control class for controlbuilder Control .
    /// </summary>
    protected HTMLControl formControl;

    /// <summary>
    /// Html Control class for the label.
    /// </summary>
    private HTMLControl labelControl;


    /// <summary>
    /// Getting the property for the Control .
    /// </summary>
    /// <history>
    /// [LuckyR] 10/8/2009 Created
    /// </history>
    public HTMLControl Form
    {
        get { return formControl; }
    }

    /// <summary>
    /// Creating a label for the Control.
    /// </summary>
    /// <history>
    /// [LuckyR] 10/8/2009 Created
    /// </history>
    public HTMLControl Label
    {
        get { return labelControl; }
    }

    /// <summary>
    /// Creating a construtor for the controlbuilder taking in Zero 
    /// arguments it creates a labl for the Control .
    /// </summary>
    /// <history>
    /// [LuckyR] 13/8/2009 Created
    /// </history>
    public ControlBuilder() { }

    /// <summary>
    /// A construtor for the controlbuilder which
    /// creates a label for the Control .
    /// </summary>
    /// <history>
    /// [LuckyR] 10/8/2009 Created
    /// </history>
    public ControlBuilder(string labelName)
    {
        Label label = new Label();
        label.Text = labelName;
        label.Width= 200;
        labelControl = new HTMLControl(label);
    }


    /// <summary>
    /// Control build property that is used to biuld the Html 
    /// markup for the created Control.
    /// </summary>
    /// <history>
    /// [LuckyR] 10/8/2009 Created
    /// </history>
    public string BuildControl()
    {
        this.CreateControl();
        this.SetAttribute();
        return this.RenderHTML();
    }

    /// <summary>
    /// Render Html tags for the Control with label . 
    /// </summary>
    /// <history>
    /// [LuckyR] 10/8/2009 Created
    /// </history>
    public string RenderHTML()
    {
        return labelControl.RenderHTML() + ": " + formControl.RenderHTML();
    }

    /// <summary>
    /// Used to Set Attributes for the Control .
    /// </summary>
    /// <history>
    /// [LuckyR] 13/8/2009 Created
    /// </history>
    protected virtual void SetAttribute() { }

    /// <summary>
    /// Used to create the Control . 
    /// </summary>
    /// <history>
    /// [LuckyR] 13/8/2009 Created
    /// </history>
    protected virtual void CreateControl() { }

    /// <summary>
    /// A list of all the Controls that will be created during the 
    /// program run .
    /// </summary>
    private IList<ControlBuilder> Controls = new List<ControlBuilder>();

    /// <summary>
    /// A property to add Control to the ControlBuilder that are created by 
    /// the user.
    /// </summary>
    /// <history>
    /// [LuckyR] 13/8/2009 Created
    /// </history>
    /// <param name="Control">Controls from the controlbuilder class</param>
    public void AddControl(ControlBuilder Control)
    {
        Controls.Add(Control);
    }

    /// <summary>
    /// A property to display the Controls that are created by 
    /// the user.
    /// </summary>
    /// <history>
    /// [LuckyR] 13/8/2009 Created
    /// </history>
    public string Display()
    {
        string Html = string.Empty;

        foreach (ControlBuilder builder in Controls)
        {
            Html += builder.BuildControl();
            Html += "<br /><br />";
        }

        return Html;
    }
} 

}

так я создаю элемент управления

public class TextBoxBuilder : ControlBuilder
{
    /// <summary>
    /// Creating a web Control textBox.
    /// </summary>
    private TextBox textBox;

    /// <summary>
    /// Creating an Id to add as an attribute .
    /// </summary>
    private string Id;

    /// <summary>
    /// Creating an Value to add as an attribute .
    /// </summary>
    private string Value; 

    /// <summary>
    /// Creating a Textbox constructor which takes in LabelName and Id. 
    /// to create a label for the Control. 
    /// </summary>
    /// <history>
    /// [LuckyR] 10/8/2009 Created
    /// </history>
    public TextBoxBuilder(string labelName, string id , string value): base(labelName)
    {
        this.Id = id;
        this.textBox = new TextBox();
        this.Value = value;
    }

    /// <summary>
    /// Used to Set properties for the Control . 
    /// </summary>
    /// <history>
    /// [LuckyR] 10/8/2009 Created
    /// </history>
    protected override void SetAttribute()
    {
        this.textBox.ID = this.Id;
        this.textBox.Text = this.Value;
    }

    /// <summary>
    /// Used to create the Control . That is done by calling the HtmlControl class 
    /// which inturn renders the particular Control for us .
    /// </summary>
    /// <history>
    /// [LuckyR] 10/8/2009 Created
    /// </history>
    protected override void CreateControl()
    {
        this.formControl = new HTMLControl(this.textBox);
    }
} 

}

В моем домашнем контроллере я сделал это ...

      public ActionResult Create()
      {
         ///Where i am contacting the linq to sql classs for performing ths operagtion
         foreach (var control in Rep.GetData(ScreenName))
         {
            string Type = control.Type;
            string value = null;
            if (id != Guid.Empty)
            {
                value = DataObj.GetValue(control.TableName, control.ControlName, id);
            }

            switch (Type)
            {
                case ("TextBox"):
                    /// Buliding a textBox box 
                    controlbuilder.AddControl(new TextBoxBuilder(control.Field, control.ControlName, value));
                    break;

                case ("CheckBox"):
                    /// Bulidig a CheckBox .
                    controlbuilder.AddControl(new CheckBoxBuilder(control.Field, control.ControlName , value));
                    break;

                case ("DatePicker"):
                    /// Bulidig a DatePicker .
                    controlbuilder.AddControl(new DatePicker(control.Field, control.ControlName, value));
                    break;

                case ("DropDownList"):
                    ///Building a dropdownlist.
                    List<string> list = DataObj.GetDropDownValues(control.Id);
                    controlbuilder.AddControl(new DropDownListBuilder(control.Field, control.ControlName, list,value));
                    break;

                case ("TextArea"):
                    /// Building a textBox area .
                    controlbuilder.AddControl(new TextArea(control.Field, control.ControlName , value));
                    break;

                default:
                    break;
            }
        }

        return View(controlbuilder);
       }

Страница просмотра выглядит следующим образом ...

<% using (Html.BeginForm())
   {%>
<fieldset>
    <legend>Fields</legend>
    <p>
        <%= ViewData.Model.Display() %>
    </p>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
<% } %>
<div>
    <%=Html.ActionLink("Back to List", "Index")%>
</div>

так как я передаю свой класс в представление, я могу получить все данные там с помощью .display.

1 Ответ

6 голосов
/ 10 августа 2009

В ASP.NET MVC больше нет концепции элементов управления.

У вас есть два варианта:

  1. Когда пользователь нажимает кнопку, вы обрабатываете этот запрос POST в действии контроллера, устанавливаете своего рода флаг в вашей модели представления, чтобы теперь отображать текстовое поле, а затем возвращаете то же представление, которое в свою очередь будет смотреть флаг и сгенерировать текстовое поле, если требуется. Это повлечет за собой полное обратное путешествие, которое будет несколько похоже на обратную передачу в WebForms.

  2. Вы делаете это на месте с помощью JavaScript. Вы перехватываете событие нажатия кнопки и вставляете HTML-элемент input / textarea в структуру документа.

...