Asp.Net在FormView中使用默认值

时间:2013-10-11 08:06:45

标签: c# asp.net entity-framework default formview

我是Entity Framework和Asp.Net的新手,我正试图弄清楚如何将特定字段的默认值设置为FormView。这是基本代码:

<asp:FormView runat="server" ID="addObjForm"
    ItemType="MySpace.Models.Obj" 
    InsertMethod="insertObj" DefaultMode="Insert"
    RenderOuterTable="false" OnItemInserted="obj_ItemInserted">
    <InsertItemTemplate>
        <fieldset>
            <ol>
                <asp:DynamicEntity ID="DynamicEntity1" runat="server" Mode="Insert" />
            </ol>
            <asp:Button ID="Button1" runat="server" Text="Insert" CommandName="Insert" />
            <asp:Button ID="Button2" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
</asp:FormView>

背后的代码:

public void insertObj()
    {
        var item = new Obj();
        TryUpdateModel(item);
        if (ModelState.IsValid)
        {
            using (WebContext db = new WebContext())
            {
                db.Objects.Add(item);
                db.SaveChanges();
            }
        }
    }

假设我必须为使用外键引用其父对象的子对象插入数据,并通过GET将此外键传递给Web表单。如何自动将此值设置为FormView?

1 个答案:

答案 0 :(得分:0)

使用ItemCreated事件

protected void addObjForm_ItemCreated(object sender, EventArgs e)
{
    if (addObjForm.CurrentMode == FormViewMode.Insert)
    {
        // Set your default value here by the below sample ways 
    }
}

sample 1

sample 2