我需要在网页上的数据库表中编辑信息。但我遇到麻烦,TextArea中的数据没有改变。 第一:显示TextArea中的更改数据。 其次:保存更改数据。 这是我的C#代码
public partial class Edit : System.Web.UI.Page
{
Model1 context = new Model1();
string str;
int ID;
protected void Page_Load(object sender, EventArgs e)
{
str = Request.QueryString["Id"];
ID = Convert.ToInt32(str);
FirstArea2.Value = EditQuestion().name;
editor.Value = System.Web.HttpUtility.HtmlDecode(EditQuestion().details.ToString());
}
protected void Send_Click_Save(object sender, EventArgs a)
{
EditQuestion().name = FirstArea2.Value;
EditQuestion().details = editor.Value;
context.SaveChanges();
Response.Redirect("FirstPage.aspx");
}
public questions2 EditQuestion()
{
questions2 question = (from x in context.questions2
where x.id == ID
select x).FirstOrDefault();
return question;
}
}
和HTML
<textarea id="FirstArea2" name="FirstArea" runat="server" style="width:57.5%;height:16px;" required="required"></textarea>
<textarea id="editor" runat="server" style="width:60%;height:200px;" required="required"> </textarea>
<asp:Button ID="Save" runat="server" Text="Save" OnClick="Send_Click_Save" />
答案 0 :(得分:1)
我建议阅读一些有关实体框架的教程,例如:http://www.entityframeworktutorial.net/EntityFramework4.3/update-entity-using-dbcontext.aspx
每次调用EditQuestion()时,您都会从数据库中获取最新版本的问题。 我建议使用以下代码来更新你的question2对象。
using(var context = new Model1())
{
questions2 question = (from x in context.questions2
where x.id == ID
select x).FirstOrDefault();
if(question != null){
question.name = newName;
question.details = newDetails;
}
context.SaveChanges();
}
答案 1 :(得分:0)
考虑如何使用您的代码:
EditQuestion().name = FirstArea2.Value;
EditQuestion().details = editor.Value;
context.SaveChanges();
您加载两个不同的问题实例,并更改其值。加载第二个时丢失第一个。这不是你想要的。
相反,你可以做类似的事情:
using(var context = new Model1()) // avoid to instantiate context at the page load, it's better to keep it short lived
{
questions2 question = context.questions2.FirstOrDefault(q => q.id == ID); // this does the same as your code but it's shorter
if (question != null)
{
question.name = newName;
question.details = newDetails;
}
else
{ // handle insert if needed }
context.SaveChanges();
}
在你的页面加载中你会犯同样的错误,你的EditQuestion()方法是一种不好的做法,即使对于读取数据也是如此,因为它涉及在每次调用时无法访问数据库。
答案 2 :(得分:0)
我解决了我的问题!如果您有兴趣:
protected void Page_Load(object sender, EventArgs e)
{
str = Request.QueryString["Id"];
ID = Convert.ToInt32(str);
if (!IsPostBack)
{
FirstArea2.Value = EditQuestion().name;
editor.Value =System.Web.HttpUtility.HtmlDecode(EditQuestion().details.ToString());
}
}
感谢您的回答