WEBFORM 后台表单模型绑定


效果图

代码

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
    <input type="text" name="A" /><hr />
    <input type="text" name="B" /><hr />
    <input type="text" name="C" /><hr />
    <input type="text" name="D" /><hr />
    <input type="text" name="E" /><hr />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <hr />
    <asp:UpdatePanel ID="UpdatePanel2" runat="server">
        <ContentTemplate>
            <asp:Literal ID="LA" runat="server"></asp:Literal><hr />
            <asp:Literal ID="LB" runat="server"></asp:Literal><hr />
            <asp:Literal ID="LC" runat="server"></asp:Literal><hr />
            <asp:Literal ID="LD" runat="server"></asp:Literal><hr />
            <asp:Literal ID="LE" runat="server"></asp:Literal><hr />
        </ContentTemplate>
    </asp:UpdatePanel>
</div>
</form>

    public partial class AutoBind : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        AutoBindModel model = new AutoBindModel();

        var properties = model.GetType().GetProperties();

        foreach (var prop in properties)
        {
            object value = new object();
            try
            {
                value = Convert.ChangeType(Request.Form[prop.Name], prop.PropertyType);
                prop.SetValue(model, value, new object[] { });
            }
            catch
            {
            }
        }

        LA.Text = model.A.ToString();
        LB.Text = model.B.ToString();
        LC.Text = model.C.ToString();
        LD.Text = model.D.ToString();
        LE.Text = model.E.ToString();

    }
}

public class AutoBindModel
{
    public int A { get; set; }
    public double B { get; set; }
    public string C { get; set; }
    public DateTime D { get; set; }
    public bool E { get; set; }
}

知识共享许可协议
《WEBFORM 后台表单模型绑定》 常伟华 创作。
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议 | 3.0 中国大陆许可协议进行许可。

站内公告

A PHP Error was encountered

Severity: Core Warning

Message: PHP Startup: zip: Unable to initialize module Module compiled with module API=20060613 PHP compiled with module API=20090626 These options need to match

Filename: Unknown

Line Number: 0

Backtrace: