#c# #asp.net
#c# #asp.net
Вопрос:
У меня есть две страницы. В posts.aspx у меня есть одна загрузка изображения, текстовое поле и кнопка отправки. Когда я нажимаю на кнопку отправки, содержимое изображения и текстовой области сохраняется в базе данных при входе в систему. Эти изображения, содержимое должны привязывать gridview на другой странице (т.е. lists.aspx). Я не могу получить значение содержимого posts.aspx.
Posts.aspx
<div>
<asp:FileUpload ID="fuPostImageUrl" runat="server" Style="margin-left: 80px" />
<br>
<asp:Label ID="lblPostTitle" runat="server"
Style="font-family: comfortaa, sans-serif; margin-left: 25px; color: red; font-size: 25px; font-weight: bold;"
Text="Please Enter Your Post Title : ">
</asp:Label>
<asp:TextBox ID="txtPostTitle" runat="server" TextMode="MultiLine" Style="margin-left: 13px">
</asp:TextBox>
<br>
<asp:Label ID="lblPostDetails" runat="server"
Style="font-family: comfortaa, sans-serif; margin-left: 25px; color: red; font-size: 25px; font-weight: bold;"
Text="Please Enter Your Comments : ">
</asp:Label>
<textarea id="txtPostDetails" runat="server"
class="comments"
cols="20"
rows="5"
style="width: 592px;"
onfocus="this.placeholder = ''"
onblur="this.placeholder = 'Give Us Your Valid Comment'"
placeholder="Give Us Your Valid Comment">
</textarea>
<asp:Button ID="btnEnteredPostComment" runat="server"
Style="-webkit-border-radius: 10px; -ms-border-radius: 10px; -moz-border-radius: 10px;
border-radius: 10px; margin-left: 850px; margin-top: 15px;border: 0px solid; padding: 10px;"
Text="Enter Your Post"
ValidationGroup="UsersPostComment"
OnClick="btnEnteredPostComment_Click" />
</div>
Posts.aspx.cs
protected void btnEnteredPostComment_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(@"Data Source=113.193.127.110;Initial Catalog=IW_Dev_MindVsHeart;User ID=IW_Dev_MindVsHeart;Password=[IW_Dev_MindVsHeart123$]");
connection.Open();
string link = "";
if (Session["UserId"] != null)
{
if (fuPostImageUrl.HasFile)
{
string fname = fuPostImageUrl.FileName;
string fpath = Server.MapPath("~/Images/");
int flen = fuPostImageUrl.PostedFile.ContentLength;
string fext = Path.GetExtension(fname);
fext = fext.ToLower();
link = "~/Images/" fname;
if (flen < 1048576)
{
if (fext == ".jpg" || fext == ".png" || fext == ".gif" || fext == ".bmp")
{
fuPostImageUrl.SaveAs(fpath fname);
}
else
{
Response.Write("<script>alert('Only image files are allowed');</script>");
}
}
else
{
Response.Write("<script>alert('Max file size allowed is 1 MB');</script>");
}
}
SqlCommand command = new SqlCommand("SavePost", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@postimageurl", link);
command.Parameters.AddWithValue("@title", txtPostTitle.Text);
command.Parameters.AddWithValue("@content", txtPostDetails.InnerText);
command.Parameters.AddWithValue("@createdby", Session["UserId"]);
command.ExecuteNonQuery();
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Your Comment Posted Successfully . Do You Want Post another one ? . ');", true);
txtPostTitle.Text = "";
txtPostDetails.InnerText = "";
}
else
{
txtPostTitle.Text = "";
txtPostDetails.InnerText = "";
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Your Session Expired or Login to Comment . ');", true);
}
connection.Close();
}
lists.aspx
<div class="rounded_corners" style="width: 300px">
<asp:GridView ID="gvrecords" runat="server"
AlternatingRowStyle-BackColor="White"
AutoGenerateColumns="false"
DataKeyNames="PostId"
HeaderStyle-BackColor="#3AC0F2"
HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2"
RowStyle-ForeColor="#3A3A3A"
Width="300"
OnRowCommand="gvrecords_RowCommand"
OnRowDataBound="gvrecords_RowDataBound" >
<Columns>
<asp:ImageField DataImageUrlField="PostImageUrl" HeaderText="Post Image"
ControlStyle-Height="100"
ControlStyle-Width="100" />
<asp:BoundField DataField="Title" HeaderText="Post Title" />
<asp:BoundField DataField="Content" HeaderText="Post Comment" />
<asp:TemplateField HeaderText="Delete Comment">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server"
CommandName="Delete_Comment"
CommandArgument='<%# Eval("PostId") %>'>
Delete Comment
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
lists.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
BindUserDetails();
}
}
protected void BindUserDetails()
{
SqlConnection connection = new SqlConnection(@"Data Source=113.193.127.110;Initial Catalog=IW_Dev_MindVsHeart;User ID=IW_Dev_MindVsHeart;Password=[IW_Dev_MindVsHeart123$]");
connection.Open();
if (Session["UserId"] != null)
{
SqlCommand command = new SqlCommand("BindExistsUserPosts", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@userid", Session["UserId"]);
//command.Parameters.AddWithValue("@userid", Session["PostId"]);
command.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
gvrecords.DataSource = ds;
gvrecords.DataBind();
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please Login to Comment . ');", true);
}
connection.Close();
}
protected void gvrecords_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete_Comment")
{
int posid = Convert.ToInt32(e.CommandArgument);
SqlConnection connection = new SqlConnection(@"Data Source=113.193.127.110;Initial Catalog=IW_Dev_MindVsHeart;User ID=IW_Dev_MindVsHeart;Password=[IW_Dev_MindVsHeart123$]");
connection.Open();
SqlCommand command = new SqlCommand("DeleteExistsUserPost", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@postid", posid);
int result = command.ExecuteNonQuery();
connection.Close();
if (result == 1 amp;amp; Session["UserId"] != null)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" Title " Post deleted Successfully')", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "alert('Please Login to Delete Comment . ');", true);
}
BindUserDetails();
}
}
protected void gvrecords_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string title = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Title"));
LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("lnkdelete");
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" title "')");
}
}
Комментарии:
1. Ваш файл успешно сохраняется в пути к файлу?
2. ДА. Я сохраняю файл по правильному пути к файлу..
3. позвольте мне прояснить .. когда вы публикуете что-то со страницы Posts.aspx.cs, все данные сохраняются в БД, верно? и когда вы повторно заходите на сайт, у вас есть GirdView, который должен отображать опубликованный контент этого конкретного пользователя? если я ошибаюсь, пожалуйста, уточните .. и какую ошибку вы получаете? пожалуйста, опубликуйте свою StoredProcedure тоже..
4. Когда я захожу в систему и публикую что-то в posts.aspx и перехожу на другую страницу под названием lists.aspx .На этой странице я хочу получить доступ к posts.aspx, публикуя содержимое в стиле gridview.
5. Если файл сохранен правильно, проблема в том, что загруженный файл не сохранен в базе данных, верно? Или сохраненная запись не отображается в виде сетки?
Ответ №1:
Просто попробуйте следующее:
lists.aspx.cs
Изменить с:
if (IsPostBack)
{
BindUserDetails();
}
Для:
if (!IsPostBack)
{
BindUserDetails();
}
Надеюсь, это вам поможет!
Комментарии:
1. тогда в чем заключалась ошибка на странице, которую вы получили? пожалуйста, укажите indetail, а также опубликуйте свой StoreProcedure тоже ..!Я пробовал этот код и должен работать нормально! Также попробуйте путем отладки узнать, получаете ли вы строки в DataSet? вероятно, вы не можете это четко объяснить …:(