How to get id value from database using ajax? .net - asp.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.

Related

How do I save data into MySql database using 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" />

How to move data from one action to another action in the same controller for forms?

How do I move data from an Iactionresult to another action result? I have been trying to display the data from the form and view it another Iactionresult? I attempt to use Tempdata but it seems like there is an error. Could anyone help me with it?
This action displays an individual product details when I click on an particular Id.
[HttpGet]
public IActionResult Details(int id)
{
string sql = String.Format(#"SELECT * FROM WBProduct
WHERE Id = {0}", id);
List<Product> lstProduct = DBUtl.GetList<Product>(sql);
if (lstProduct.Count == 0)
{
TempData["Message"] = $"Product #{id} not found";
TempData["MsgType"] = "warning";
return RedirectToAction("Index");
}
else
{
Product cdd = lstProduct[0];
return View(cdd);
}
}
I would like to display the the details of the product in this IActionResult
[HttpPost]
public IActionResult Create()
{
return View("Create");
}
View for Details:
#model Product
<div>
<div class="form-group row">
<div class="offset-sm-2"><h2>#Model.ProductName</h2></div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-5">
<img id="ImgPhoto" src="~/images/product/#Model.ProductImage" style="width:400px;" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="City">Weight: </label>
<div class="col-sm-5">
<input type="text" asp-for="ProductWeight" class="form-control" readonly />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Date">Stock :</label>
<div class="col-sm-5">
<input type="text" asp-for="ProductStock" class="form-control" readonly />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Cost">Price: </label>
<div class="col-sm-5">
<input type="text" asp-for="ProductPrice" asp-format="{0:C}" class="form-control" readonly />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Story">Description: </label>
<div class="col-sm-5">
<textarea asp-for="ProductDescription" rows="8" cols="20" class="form-control" readonly></textarea>
</div>
</div>
<div class="form-group row">
<a href="http://localhost:50528/Product/Create" class="btn btn-info" role="button" > Add to Cart </a>
</div>
</div>
Create View:
#model Product
<div class="form-group row">
<div class="offset-sm-2"><h2>#Model.ProductName</h2></div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="City">Weight: </label>
<div class="col-sm-5">
<input type="text" asp-for="ProductWeight" class="form-control" readonly />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Date">Stock :</label>
<div class="col-sm-5">
<input type="text" asp-for="ProductStock" class="form-control" readonly />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Cost">Price: </label>
<div class="col-sm-5">
<input type="text" asp-for="ProductPrice" asp-format="{0:C}" class="form-control" readonly />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="Story">Description: </label>
<div class="col-sm-5">
<textarea asp-for="ProductDescription" rows="8" cols="20" class="form-control" readonly></textarea>
</div>
</div>
The error message that I got was:
This should be a GET action, not a POST one, then you should extract the info from the TempData and pass it as parameter to the view cshtml.
TempData["Product"] = JsonConvert.SerializeObject(lstProduct[0]);
return RedirectToAction("Create");
Now you can deserialize in the Create action and retrieve your Product
[HttpGet]
public IActionResult Create()
{
// If the caller has prepared a product we can show it.
if(TempData.ContainsKey("Product"))
{
Product p = JsonConvert.DeserializeObject<Product>(TempData["Product"]);
return View(p);
}
else
return View();
}
If you want to move data from one action to another action in the same controller
just call one action from another and put data as an input parameter of another action.
To send message to Index action, at first create a class for the message:
public class ErrorMsg
{
public string Message {get; set;}
public string MessageType {get; set;}
}
Change your action Index to this:
public IActionResult Index(ErrorMsg errorMsg)
{
// if action called from another controller action, details for exapmple,
//errorMsg will contain data from that action
// otherwise errMsg will be an empty default object with empty strings
//Check if error
if(!string.IsNullOrEmpty(errorMsg.Message) ...your error code
else ....your index code here
}
Change your action details code:
public IActionResult Details(int id)
{
string sql = String.Format(#"SELECT * FROM WBProduct
WHERE Id = {0}", id);
List<Product> lstProduct = DBUtl.GetList<Product>(sql);
if (lstProduct.Count == 0)
{
var errMsg = new ErrMessage {
Message = $"Product #{id} not found",
MessageType = "warning"
}
return Index(errMsg);
}
else
{
Product cdd= lstProduct.FirstOrDefault();
//Or you can try again var cdd = lstProduct[0]; if you like it more
return View("Details", cdd);
}
}
Change your create action to this:
public IActionResult Create(Product product)
{
// if action called from another controller action, "product" will contain data //from that action
// otherwise "product" will be posted from the view or it will be an empty model with the default value fields
if(product.Id ==0) ... call add ef code
else ... call update ef code
}
And you have to add <form tag to all your views, othewise if will not post back any data, and add Product.Id hidden field inside of form:
#model Product
#using (Html.BeginForm("Create", "Product", FormMethod.Post)
{
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div>
<input type="hidden" asp-for="#Model.Id" />
<div class="form-group row">
<div class="offset-sm-2"><h2>#Model.ProductName</h2></div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-5">
<img id="ImgPhoto" src="~/images/product/#Model.ProductImage" style="width:400px;" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="City">Weight: </label>
<div class="col-sm-5">
<input type="text" asp-for="ProductWeight" class="form-control" readonly />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="ProductStock">Stock :</label>
<div class="col-sm-5">
<input type="text" asp-for="ProductStock" class="form-control" readonly />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="ProductPrice">Price: </label>
<div class="col-sm-5">
<input type="text" asp-for="ProductPrice" asp-format="{0:C}" class="form-control" readonly />
</div>
</div>
<div class="form-group row">
<label class="control-label col-sm-2" for="ProductDescription">Description: </label>
<div class="col-sm-5">
<textarea asp-for="ProductDescription" rows="8" cols="20" class="form-control" readonly></textarea>
</div>
</div>
<div class="form-group row">
<button class="btn btn-info btn-link" type="submit"> Add to Cart </button>
</div>
</div>
}

Class receiving the value reset

I'm doing insert via post, but my class is getting the zero values of the inputs.
The values of the inputs are passed via variable and corrections are displayed, but at the time of the post are coming down.
The most interesting thing is if you type inside the input, then the values come correctly.
<form method="post">
<div class="col-sm-3">
<label>SALDO</label>
<div style="border:1px solid #bbb9b9; border-radius:3px;"></div>
<br />
<div class="form-group">
<label asp-for="Caixas.ValorFinalDinheiro" class="control-label"></label>
<input asp-for="Caixas.ValorFinalDinheiro" name="Caixas.ValorFinalDinheiro" id="Caixas.ValorFinalDinheiro" class="form-control finalFundo" disabled="disabled" />
</div>
<div class="form-group">
<label asp-for="Caixas.ValorFinalCheque" class="control-label"></label>
<input asp-for="Caixas.ValorFinalCheque" class="form-control finalFundo" disabled="disabled"/>
</div>
<div class="form-group">
<label asp-for="Caixas.ValorFinalBoleto" class="control-label"></label>
<input asp-for="Caixas.ValorFinalBoleto" class="form-control finalFundo" disabled="disabled" />
</div>
<div class="form-group">
<label asp-for="Caixas.ValorFinalCartao" class="control-label"></label>
<input asp-for="Caixas.ValorFinalCartao" class="form-control finalFundo" disabled="disabled" />
</div>
<div class="form-group">
<label asp-for="Caixas.ValorFinalDeposito" class="control-label"></label>
<input asp-for="Caixas.ValorFinalDeposito" class="form-control finalFundo" disabled="disabled" />
</div>
<div class="form-group">
<label asp-for="Caixas.ValorFinal" class="control-label"></label>
<input asp-for="Caixas.ValorFinal" class="form-control" style="background-color:#9FF781" />
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input type="submit" value="Confirmar o Fechamento do Caixa" class="btn btn-primary btn-sm" />
<a asp-page="Index" class="btn btn-success btn-sm">Retorna ao Caixa</a>
</div>
</div>
</form>
[BindProperty]
public Caixas Caixas { get; set; }
public async Task<IActionResult> OnPostAsync()
{
var C = _context.Caixas.Find(Caixas.Id);
C.fechado = true;
C.DataFinal = DateTime.Now;
C.HoraFinal = DateTime.Now;
C.FuncionarioFechamentoId = _userManager.GetUserId(HttpContext.User);
C.ValorFinalDinheiro = Caixas.ValorFinalDinheiro;
C.ValorFinalCheque = Caixas.ValorFinalCheque;
C.ValorFinalBoleto = Caixas.ValorFinalBoleto;
C.ValorFinalCartao = Caixas.ValorFinalCartao;
C.ValorFinalDeposito = Caixas.ValorFinalDeposito;
C.ValorFinal = Caixas.ValorFinal;
C.ValorSaida = Caixas.ValorSaida;
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
Remove Caixas property and add it as parameter in your OnPostAsync method:
// [BindProperty]
// public Caixas Caixas { get; set; }
[HttpPost]
public async Task<IActionResult> OnPostAsync([FromBody]Caixas c)
{
// ...
}

form doesn't send parameters to correct method

I have the following registration form in `Thymleaf, the problem is when i submit the button it just redirect me to login page.
Here is my form:
<form class="form-horizontal" th:object="${newCustomer}" th:method="post" th:action="#{/dashboard/NewUserRegisteration}">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Full Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" th:field="*{name}"></input>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">address</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="address" th:field="*{address}"></input>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="phone" th:field="*{phone}"></input>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" th:field="*{password}"></input>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="confirmPass" th:field="*{confirmPass}"></input>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="submit-button" type="submit" class="btn btn-default">Submit query</button>
</div>
</div>
</form>
and here is the controller method:
#RequestMapping(method=POST, path="dashboard/NewUserRegisteration")
public String RegisterNewCustomer( #RequestParam(name = "name") UserDTO userDTO ){
System.out.println("All Users are: ");
return "redirect:"+ "/dashboard/login";
}
As you can see, i expect to see the "All Users are: " printed when i push the button but it doesn't work.
and at the end here is the UserDTO class:
#Data
#NoArgsConstructor(force = true)
public class UserDTO {
long id;
String name;
String address;
String phone;
String password;
String userName;
String confirmPass;
}
Number one, did you consider that you specified this, that redirects to login page?:
return "redirect:"+ "/dashboard/login";
If that was not your intention, then in your code, you already specified the path to follow after execution of the controller method.
In the method you may be thinking of breaking it down like this
`
#Autowired
UserRepository userRepository;
#RequestMapping(method = RequestMethod.POST, path="dashboard/NewUserRegisteration")
public String RegisterNewCustomer(Model model){
UserDTO user = new UserDTO();
model.addAttribute("newCustomer",user);
userRepository.save(user);
return "redirect:/dashboard/login";
}
`

Javascript click handlers

The task is :
I have done the form and the design bit for the web page but never came across this push: function() in javascript
I am confused on how to approach or do this task any help will be appreciated! Thank you :)
var _itq = {
push: function() {
console.log.apply(console, arguments);
}
};
_itq.push("_itq", "initialised", "ok");
<form id="commentForm" method="get" action="">
<div class="form-group">
<input class="form-control" type="email" placeholder="Enter Your Email" required>
</div>
<div class="form-group">
<div>
<input type="text" class="form-control" placeholder=" Enter Your Name" pattern=".{2,}" required title="2 characters minimum">
</div>
<div>
<input type="password" class="form-control" placeholder="Your Password" pattern=".{5,10}" required title="5 to 10 characters">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-info">Sign Up</button>
</div>
</form>
Here is the second question, this should set you on the right path for question 1.
document.getElementById('commentForm').onsubmit = function() { // attach to form submit
var email = document.getElementById("email").value; // get the email value (add id="email" to the email input in the html)
var name = document.getElementById("name").value; // get the name (add id="name" to the name input in the html)
var initials = name.split(' ').map(function(v, i) { // get the initials by splitting
return v[0] // on space and taking the 1st char
}).join('');
_itq.push(email, initials); // pass into your push
return false; // return false to stop the submit (optional depending on requirements)
};
working snippet below
var _itq = {
push: function() {
console.log.apply(console, arguments);
}
};
_itq.push("_itq", "initialised", "ok");
document.getElementById('commentForm').onsubmit = function() {
var email = document.getElementById("email").value;
var name = document.getElementById("name").value;
var initials = name.split(' ').map(function(v, i) {
return v[0]
}).join('');
_itq.push(email, initials);
return false;
};
<form id="commentForm" method="get" action="">
<div class="form-group">
<input id="email" class="form-control" type="email" placeholder="Enter Your Email" required>
</div>
<div class="form-group">
<div>
<input id="name" type="text" class="form-control" placeholder=" Enter Your Name" pattern=".{2,}" required title="2 characters minimum">
</div>
<div>
<input type="password" class="form-control" placeholder="Your Password" pattern=".{5,10}" required title="5 to 10 characters">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-info">Sign Up</button>
</div>
</form>
Try Something like this
Your HTML:
<button type="submit" class="btn btn-block btn-info" onclick="fillarr()">Sign Up</button>
JS:
function fillarr(){
_itq.push(document.getElementById("emailId").value, document.getElementById("nameId").value);
}
You still need to add an ID for your Email and Name field though

Resources