How do I save data into MySql database using ASP.NET - asp.net

I am trying to insert data into MySql database but I am not getting any errors. I have already tested out the sql query but it works in the mysql workbench but it not working in the project codes.
protected void uploadImagesBtn_Click(object sender, EventArgs e)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["CMSconnectionString"].ToString();
string name = ImgNameTB.Text;
string desc = imgDescriptionTB.Text;
string date = uploadDateTB.Text;
string constr = ConfigurationManager.ConnectionStrings["CMSconnectionString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO fyp_cms.images (ImageName, ImageDescription, UploadDate) VALUES (#imgname, #imgdesc, #imgUploadDate)"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Parameters.AddWithValue("#imgname", name);
cmd.Parameters.AddWithValue("#imgdesc", desc);
cmd.Parameters.AddWithValue("#imgUploadDate", date);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
.aspx file
<div class="card-body">
<form>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Image Name</label>
<asp:TextBox class="form-control" ID="ImgNameTB" name="imageName" placeholder="Name" runat="server" ></asp:TextBox>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Date</label>
<asp:TextBox ID="uploadDateTB" class="form-control" type="Date" name="imageuploadDate" runat="server"></asp:TextBox>
</div>
</div>
<div class="form-group">
<label for="inputAddress">Description</label>
<asp:TextBox ID="imgDescriptionTB" class="form-control" name="imageDescription" placeholder="eg. Open House 2021" runat="server"></asp:TextBox>
</div>
<label for="inputAddress">Select Image</label>
<div class="form-group col-mb-4">
<div class="custom-file">
<%--<input type="file" class="custom-file-input" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile02" aria-describedby="inputGroupFileAddon02">Choose file</label>--%>
<asp:FileUpload ID="ImageFileUpload1" runat="server" />
</div>
</div>
<label for="inputAddress">Select File</label>
<div class="input-group mb-4">
<div class="custom-file">
<%--<input type="file" class="custom-file-input" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile02" aria-describedby="inputGroupFileAddon02">Choose file</label>--%>
<asp:FileUpload ID="VideoFileUpload2" runat="server" />
</div>
</div>
<label for="inputAddress">Select Videos</label>
<div class="input-group mb-4">
<div class="custom-file">
<%--<input type="file" class="custom-file-input" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile02" aria-describedby="inputGroupFileAddon02">Choose file</label>--%>
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
</div>
</div>
<asp:Button ID="uploadImagesBtn" runat="server" class="btn btn-primary" Text="Upload" OnClick="uploadImagesBtn_Click" />
</div>
Those above are my codes, I am not sure what is the error as I have alr added an onclick function on the upload button

set form Post,enctype and button type Submit.
actually you are submitting file. form is not submitting without form enctype
<form method="post" enctype="multipart/form-data">
<asp:Button ID="uploadImagesBtn" type="submit" runat="server" class="btn btn-primary" Text="Upload" OnClick="uploadImagesBtn_Click" />

Related

How to remove space between text using Bootstrap?

I am designing the form using Bootstrap. I wanted to remove the space between send inquiry to and company name.
I am getting the output as
Send inquiry to: companyname
countryname
I want the result as
Send Inquiry to:companyname
countryname
Code:
<div class="formmain">
<fieldset class="scheduler-border">
<legend class="scheduler-border">INQUIRY DETAILS</legend>
<div class="row">
<div class="form-group">
<%--<label class="control-label input-label" for="Send Inquiry">Send inquiry to:</label>--%>
<%-- <label class="control-label col-sm-2" for="Send Inquiry">Send inquiry to:</label>--%>
<%--<h3>Send inquiry to:</h3>--%>
<label class="control-label col-sm-2" for="usr">Send inquiry to:</label>
<div class="col-sm-10">
<asp:Label ID="lbCompanyname" runat="server" Text=""></asp:Label>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-sm-2 col-sm-offset-2">
<asp:Label ID="lbcountry" runat="server" Text=""></asp:Label>
</div>
</div>
</div>
</fieldset>
</div>
I know this is a basic question. I am new to Bootstrap. I tried by putting Padding Property but it didn't work for me.
Try this:
<label class="control-label col-sm-2" for="usr">Send inquiry to:</label>
<div style="display:inline-block; vertical-align:top">
<asp:Label ID="lbCompanyname" runat="server" Text=""></asp:Label><br />
<asp:Label ID="lbcountry" runat="server" Text=""></asp:Label>
</div>

How to get id value from database using ajax? .net

I have a blog site and I made a comment panel under the article. example; user name, mail adress and comment...
I can add these fields using ajax but can't determine which article the comment is made on.
That's inputs..
<div class="form-group">
<%-- <label for="name" class="col-sm-2 control-label" style="color: #fff;">Name</label>--%>
<div class="col-sm-8">
<input type="text" class="form-control" id="t1" name="name" placeholder="Adınız" required tabindex="1">
</div>
</div>
<div class="form-group">
<%-- <label for="email" class="col-sm-2 control-label" style="color: #fff;">E-mail</label>--%>
<div class="col-sm-8">
<input type="email" class="form-control" id="t2" name="email" placeholder="E-mail Adresiniz" required>
</div>
</div>
<div class="form-group">
<%-- <label for="name" class="col-sm-2 control-label" style="color: #fff;">Message</label>--%>
<div class="col-sm-10">
<textarea id="t3" name="message" class="form-control" placeholder="Yorumunuz" rows="5" required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" style="float: right;" class="btn btn-primary" onclick="ekle()">Gönder</button>
</div>
that's commentAjax.aspx code behind;
sqlBaglantisi baglan = new sqlBaglantisi();
string adsoyad, email, yorum, makaleID;
protected void Page_Load(object sender, EventArgs e)
{
makaleID = Request.QueryString["makaleID"];
adsoyad = Request.QueryString["adsyd"].ToString();
email = Request.QueryString["em"].ToString();
yorum = Request.QueryString["yrm"].ToString();
SqlCommand cmd = new SqlCommand("insert into Yorum (yorumAdSoyad, yorumEmail, yorumIcerik, yorumResim, makaleID) values('" + adsoyad.ToString() + "','" + email.ToString() + "','" + yorum.ToString() + "','/tema/yorumm.png')", baglan.baglan());
cmd.ExecuteNonQuery();
}
and js codes;
function ekle() {
var ad = document.getElementById("t1").value;
var mail = document.getElementById("t2").value;
var yorum = document.getElementById("t3").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "yorumAjax.aspx?adsyd=" + ad + "&em=" + mail + "&yrm="+yorum, false);
xmlhttp.send(null);
document.getElementById("t1").value = "";
document.getElementById("t2").value = "";
document.getElementById("t3").value = "";
alert("Mesaj Gönderildi");
I can't understand which comment has come to which article because I can't get the value of articleID.
You can put a hidden input in your form, containing the actual ID of your article. Something like:
<input type="hidden" id="articleID" name="articleID" value="<the id for this article>" />
If you are using an MVC architecture, you can define the ID for the article in your view and then pass it to the template when rendering.
<input type="hidden" id="articleID" name="articleID" value="{{ article.id }}" />
or
<input type="hidden" id="articleID" name="articleID" value="{{ id }}" />
This way, you can then obtain the value of the article id like you did with the other fields in the javascript function.

ASP.NET Core POST method always pending

So, I'm trying to create a controller for an existing table in my database.
This is my Create method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ArticleCategoryViewModel model)
{
ArticleCategory cat = new ArticleCategory { Code = model.Code, Name = model.Name, Description = model.Description, VATId = model.VATId };
if (ModelState.IsValid)
{
_context.ArticleCategories.Add(cat);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["VATId"] = new SelectList(_context.VATs, "Id", "Percentage");
return View(model);
}
This is the form from cshtml file for create:
<form asp-action="Create" class="form-horizontal bordered-group" role="form">
<div class="form-horizontal">
<h4>ArticleCategoryViewModel</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Code" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Code" class="form-control" />
<span asp-validation-for="Code" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Description" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Name" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="VATId" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="VATId" class ="form-control" asp-items="#((IEnumerable<SelectListItem>)ViewData["VATId"])"></select>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default submit" />
</div>
</div>
</div>
</form>
Getting the information from database works, like get for index and details and edit, but when i try to post something like on create or after editing and i click submit button, its just pending. I tried every solution that i could find on the web but nothing works and i have no more ideas.
No logs are written, no error is thrown, nothing happens and i dont know why.
If i put a breakpoint inside the create method, it will not hit, so no debug.
Any ideas ?

fetching and populating values in bootstrap modal popup

This is what I'm trying to achieve here. The user clicks on a button and the bootstrap modal popup appears. The user enters the event id value in the text box of the modal popup and I want information regarding the event to be displayed on the other fields in the modal popup.
I wrote a function under txtEventId_TextChanged event and I was able to get the value entered in the event id textbox. I was able to pass that value to the database and retrieve it's corresponding values from database as well.
My problem now is that I'm not able to display those data in the modal popup.
Here is the HTML Code :
<!-- Maintainenance Modal -->
<div class="modal fade" id="maintenanceModal" role="dialog" tabindex = -1 aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false">
<div class="modal-dialog">
<!-- Maintaineance Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Maintain Event</h4>
</div>
<div class="row">
<div class="col-xs-2">
<div class ="form-group">
<label for="eventID" id="lblEventId">EventID</label>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<asp:TextBox ID="txtEventId" runat="server" CssClass="form-control dialogtextbox" AutoPostBack="false" OnTextChanged="txtEventId_TextChanged"></asp:TextBox>
</div>
</div>
</div>
<asp:HiddenField ID="HiddenField1" runat="server" />
<div class="modal-body">
<div class="EventsIcons">
<div class ="form-group">
<label for="MaintainDropDown" id="MaintainEventLabel">Select The Event Type </label>
<select id="MaintainDropDown" runat="server" class="btn btn-default dropdown-toggle eventdropdown" data-toggle="dropdown" aria-expanded="true">
<option value="WorkAnniversary">WORKANNIVERSARY</option>
<option value="Birthday">BIRTHDAY</option>
<option value="Community">COMMUNITY</option>
<option value="FoodSafety">FOOD SAFETY</option>
<option value="Health&Safety">HEALTH & SAFETY</option>
<option value="Holiday">HOLIDAY</option>
<option value="Maintenance">MAINTENANCE</option>
<option value="QualityAudit">QUALITY AUDIT</option>
<option value="SocialEvent">SOCIAL EVENT</option>
<option value="Stat-Holiday">STAT-HOLIDAY</option>
<option value="Sustainability">SUSTAINABILITY</option>
<option value="TownHall">TOWN HALL</option>
<option value="Visitor">VISITOR</option>
<option value="Wellness">WELLNESS</option>
</select>
</div>
</div>
<div class="Description">
<label for="description" id="MaintainDescription">Description</label>
<textarea class="form-control" rows="5" id="maintainTxtDescription" name="eventdescription" runat="server"></textarea>
</div>
<div class="row">
<div class="col-xs-2">
<div class="form-group">
<label id="Label3">Start Time</label>
</div>
</div>
<div class='col-xs-6'>
<div class="form-group">
<div class='input-group date' id="maintainStartDate">
<asp:TextBox ID="maintainTxtStartDate" runat="server" CssClass="form-control dialogtextbox"></asp:TextBox>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="col-xs-4">
<div class="form-group">
<div class="input-group date" id="startTime">
<asp:TextBox ID="maintainTxtStartTime" runat="server" CssClass="form-control dialogtextbox"></asp:TextBox>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<div class="form-group">
<label id="Label4">End Time</label>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<div class="input-group date" id="endDate">
<asp:TextBox ID="maintainTxtEndDate" runat="server" CssClass="form-control dialogtextbox"></asp:TextBox>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="col-xs-4">
<div class="form-group">
<div class="input-group date" id="endTime">
<asp:TextBox ID="maintainTxtEndTime" runat="server" CssClass="form-control dialogtextbox"></asp:TextBox>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-offset-1 col-xs-6">
<div class="form-group">
<asp:CheckBox ID="maintainChkBoxAllDayEvents" runat="server" CssClass="checkbox" Text="All Day Event" OnClick="document.getElementById('maintainTxtStartTime').disabled = this.checked;document.getElementById('maintainTxtEndTime').disabled = this.checked;" />
</div>
</div>
<div class="col-xs-offset-1 col-xs-4">
<div class="form-group">
<asp:Button ID="btnMaintainSubmit" runat="server" Text="SUBMIT"
CssClass="btn btn-group-justified btn-success" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
And here is my code behind code.
protected void txtEventId_TextChanged(object sender, EventArgs e)
{
BusinessLogicLayer BL = new BusinessLogicLayer();
EventId = Convert.ToInt32(txtEventId.Text);
try
{
DataTable dt = BL.BLGetEventDetails(EventId);
foreach (DataRow row in dt.Rows)
{
StartDate = row["StartDate"].ToString();
EndDate = row["EndDate"].ToString();
StartTime = row["StartTime"].ToString();
EndTime = row["EndTime"].ToString();
EventDescription = row["EventDescription"].ToString();
EventType = row["EventType"].ToString();
if (StartDate.Equals(""))
{
MessageBox.Show("EventId Does Not Exists");
maintainTxtStartDate.Text = "";
maintainTxtStartTime.Text = "";
maintainTxtEndDate.Text = "";
maintainTxtEndTime.Text = "";
MaintainDropDown.Disabled = true;
}
else
{
maintainTxtStartDate.Text = StartDate;
maintainTxtStartTime.Text = StartTime;
maintainTxtEndDate.Text = EndDate;
maintainTxtEndTime.Text = EndTime;
MaintainDropDown.Value = EventType;
maintainTxtDescription.InnerText = EventDescription;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "txtEventId_TextChanged", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
If I specify AutoPostBack="true" for txtEventId then the popup disappears from the screen after I input the value and hit enter. If I set the AutoPostBack = "false" then it is not populating the values as the control is not going to txtEventId_TextChanged function. I do not want to set AutoPostBack="true" because during postback the whole page will reload and the modal popup will disappear. I tried setting scriptmanager and updatepanel for it but since I have already an another existing scriptmanager and updatepanel added in the Default.aspx page, I'm not able to add a new one to it.
Please let me know what I'm doing wrong and how to rectify this. Your guidance is highly appreciated.
You have two options:
RegisterStartupScript
Use the RegisterStartupScript at the end of your method to send JS code to the client, you will send the call to your modal like this
ScriptManager.RegisterStartupScript(this, typeof(Page), "callModal",
"$('#maintenanceModal').modal();", true);
This is the easiest way to accomplish what you want
PageMethods
You can use the PageMethods to return a JSON with the values you want to display, this way you don't need to do a Postback, and you will get the info you want. See the requirements and how to use PageMethods

MVC Controller doesn't control the view

I have a button called in my view like this one
<form>
<div class="field">
<label for="product-name">Product Name</label><br />
#Html.TextBoxFor(x=> x.Name, new {id="product-name",required="required"}) <br />
<span class="helper">Give your product a name.</span>
#ViewBag.mm
</div>
<div class="field">
<label for="product-variety">Product Variety</label><br />
<input id="product-variety" type="text" /><br />
<span class="helper">Optionally, give your product a variety.</span>
</div>
<div class="field">
<label for="product-description">Description</label><br />
<input id="product-description" type="text" /><br />
<span class="helper">Add an optional description to help identify your product.</span>
</div>
<div class="field">
<label for="product-comments">Comments</label><br />
<textarea id="product-comments"></textarea><br />
<span class="helper">Add any further information or comments relating to this product.</span>
</div>
<input id="product-save-return" type="submit" value="Add Product and Return to Products" class="green-button" /> <input id="product-save-associate" type="button" value="Add Product and Associate with Sites" class="green-button" /> <input id="file-cancel" type="button" value="Cancel" class="green-button" />
and in the controller I have a function like this
[HttpPost]
public ActionResult Add(Product product)
{
SupplierContext db = new SupplierContext();
Response.Write("Inside");
ViewBag.mm = "xyz";
if (ModelState.IsValid)
{
product.Key = Guid.NewGuid();
product.Type = ProductType.Chemical;
product.Status = EntityStatus.Default;
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
but when i click the button, the function in the controller doesn't work.
Is your button within a form/action? In Razor it would simply just be a case of adding your form elements within the following syntax:
#using (Html.BeginForm())
{
<div class="field">
<label for="product-name">Product Name</label><br />
#Html.TextBoxFor(x=> x.Name, new {id="product-name",required="required"}) <br />
<span class="helper">Give your product a name.</span>
#ViewBag.mm
</div>
<div class="field">
<label for="product-variety">Product Variety</label><br />
<input id="product-variety" type="text" /><br />
<span class="helper">Optionally, give your product a variety.</span>
</div>
<div class="field">
<label for="product-description">Description</label><br />
<input id="product-description" type="text" /><br />
<span class="helper">Add an optional description to help identify your product.</span>
</div>
<div class="field">
<label for="product-comments">Comments</label><br />
<textarea id="product-comments"></textarea><br />
<span class="helper">Add any further information or comments relating to this product.</span>
</div>
<input id="product-save-associate" type="button" value="Add Product and Associate with Sites" class="green-button" /> <input id="file-cancel" type="button" value="Cancel" class="green-button" />
<input id="product-save-return" type="submit" value="Add Product and Return to Products" class="green-button" />
}
This could be why it is not picking up the function in the controller. You could do this in javscript too with an AJAX post...
You can also use an ActionLink:
#Html.ActionLink("Add Product and Return to Products", "Add", "YourController")
Though this will be a link instead of a button.

Resources