[英]ASP.NET C# Form Submit | Can my function be shorter and faster?
I am starting a project and I have an Onclick
function running in the code behind of my web form. 我正在启动一个项目,并且在Web表单后面的代码中运行了一个
Onclick
函数。 I was curious if there was a way to make the code shorter and/or faster? 我很好奇是否有办法使代码更短或更短?
protected void PageSubmit_Click(object sender, EventArgs e)
{
string storedProc = "";
string successMsg = "";
DataTable dt = new DataTable();
if (hfPageID.Value.Length > 0)
{
storedProc = "pageUpdate";
successMsg = "Page updated!";
}
else
{
storedProc = "pageInsert";
successMsg = "Page inserted!";
}
using (SqlConnection con = new SqlConnection(Global.conString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(storedProc, con))
{
if (storedProc == "pageUpdate")
{
cmd.Parameters.Add("@originalID", SqlDbType.VarChar).Value = hfPageID.Value;
}
cmd.Parameters.Add("@title", SqlDbType.VarChar).Value = Global.SafeSqlLiteral(txtPage.Text, 1);
cmd.Parameters.Add("@contentTypeID", SqlDbType.VarChar).Value = rblContentTypesGetAll.SelectedValue;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
con.Close();
//Update Content Page Repeater
using (SqlCommand cmd = new SqlCommand("pageGetAll", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
Session["formProcessed"] = successMsg;
Response.Redirect(redirectURL);
}
Also, I set up a check in the stored procedure to fail the pageUpdate
if a title conflicts with an existing title. 另外,如果标题与现有标题冲突,我将在存储过程中设置检查以使
pageUpdate
失败。 How can I check if it actually updated when it's coming back from the stored procedure? 从存储过程返回时,如何检查它是否实际上已更新?
ALTER PROCEDURE [dbo].[pageUpdate]
@originalID uniqueidentifier,
@contentTypeID varchar (100),
@title varchar (100)
AS
UPDATE
pages
SET
contentTypeID = COALESCE (@contentTypeID, contentTypeID),
title = COALESCE (@title, title)
WHERE
ID = @originalID
AND
NOT EXISTS
(
SELECT
*
FROM
pages
WHERE
title = @title
)
There's a number of things you could do that would certainly help readability and code reuse. 您可以做很多事情,这些无疑有助于提高可读性和代码重用性。
Seperate your page/UI logic from the database logic. 将页面/ UI逻辑与数据库逻辑分开。 ie have a class that handled data access and call that from your page rather than have it on the click event.
例如,拥有一个处理数据访问并从您的页面调用该类的类,而不是在click事件上进行处理。 If you wanted this data elsewhere, you'd have to copy and paste the code rather than just call the same method on a common object.
如果要在其他地方使用此数据,则必须复制并粘贴代码,而不仅仅是在公共对象上调用相同的方法。
Furthermore to cut down your database code, you could look at using a Data Access Application Block as featured in the Enterprise Library like these here . 此外,为了减少数据库代码,您可以考虑使用像此处所示的企业库中的数据访问应用程序块。 It'll handle connections and exceptions for you amongst other benefits listed in the documentation.
它会为您处理连接和异常,以及文档中列出的其他好处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.