我在webform中有一个简单的formview和简单的模型绑定:
<asp:FormView ID="frm" ItemType="SabaDoor2.Models.Content" SelectMethod="frm_GetItem" UpdateMethod="frm_UpdateItem" DataKeyNames="Id" runat="server">
<ItemTemplate>
<fieldset>
<legend>
<asp:Label ID="lblName" Text='<%# Item.Name %>' runat="server"></asp:Label>
</legend>
<p>
<label>descripion :</label>
<asp:Label ID="lblDescription" Text='<%# Item.Description %>' runat="server"></asp:Label>
</p>
<p>
<asp:Button ID="btnEdit" Text="edit" CommandName="Edit" runat="server" />
</p>
</fieldset>
</ItemTemplate>
<EditItemTemplate>
<fieldset>
<legend>
<asp:Label ID="lblName" Text='<%# Item.Name %>' runat="server"></asp:Label>
</legend>
<p>
<label>description :</label>
<asp:TextBox ID="txt" Text='<%# Item.Description %>' runat="server" ></asp:TextBox>
</p>
<p>
<asp:Button CommandName="Update" ValidationGroup="mainPropertyGroup" runat="server" ID="btnUpdate" Text="update" />
<asp:Button CommandName="Cancel" ValidationGroup="mainPropertyGroup" runat="server" ID="btnCancel" Text="cancel" />
</p>
</fieldset>
<br />
</EditItemTemplate>
</asp:FormView>
并在代码中:
Models.Model1Container _db = new Models.Model1Container();
protected void Page_Load(object sender, EventArgs e)
{
bindEvents();
lblResult.ForeColor = System.Drawing.Color.Green;
lblResult.Text = "";
if (!IsPostBack)
{
}
else
{
}
}
private void bindEvents()
{
frm.ItemUpdated += frm_ItemUpdated;
}
void frm_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
{
if (e.Exception == null)
{
lblResult.ForeColor = System.Drawing.Color.Green;
lblResult.Text = "done!";
}
else
{
lblResult.ForeColor = System.Drawing.Color.Red;
lblResult.Text = "error:" + e.Exception.Message;
e.KeepInEditMode = true;
}
}
public SabaDoor2.Models.Content frm_GetItem([System.Web.ModelBinding.QueryString("Id")]int? Id)
{
return _db.Contents.Find(Id);
}
// The id parameter name should match the DataKeyNames value set on the control
public void frm_UpdateItem(int Id)
{
SabaDoor2.Models.Content item = null;
item = _db.Contents.Find(Id);
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", Id));
return;
}
var result = TryUpdateModel(item);
if (ModelState.IsValid)
{
_db.SaveChanges();
}
}
public override void Dispose()
{
_db.Dispose();
base.Dispose();
}
tryUpdateModel 返回 true ,但我的模型(说明字段)未更新 :(
答案 0 :(得分:4)
我发现逻辑错误: 我必须初始化 item.Name 的 BindItem.Name 属性instd
Text='<%# BindItem.Description %>'