ASP.NET on button click event - asp.net

Hello I'm new to cshtml and I have web pages in ASP.NET Razor v2 I would like to insert some data into DB on button click. These data are provided from various textboxes and also uploading picture. May I please know how to how to provide action on button click?
I tried this in my cshtml file :
<button type="submit" name="action" value="insertRegistered">Uložit</button>
#if (action == "insertRegistered")
{
var db1 = Database.Open("StarterSite");
var sql = "UPDATE services SET FileName=#0, FileContent=#1, MimeType=#2 WHERE IDservice=6";
db1.Execute(sql, fileName, fileContent, fileMime);
}

In WebMatrix, you can accomplish this in this way:
Razor code:
#{
var fileName = "";
var fileContent = "";
var fileMime = "";
var IDservice = "";
#*TEST CODE *#
#*if (!IsPost)
{
IDservice = "1";
var db = Database.Open("StarterSite");
var dbCommand = "SELECT * FROM services WHERE IDservice = #0";
var row = db.QuerySingle(dbCommand, IDservice);
fileContent = row.fileContent;
fileMime = row.MimeType;
fileName = row.fileName;
} *#
if (IsPost)
{
fileName = Request.Form["fileName"];
fileContent = Request.Form["fileContent"];
fileMime = Request.Form["fileMime"];
IDservice = Request.Form["IDservice"];
var db1 = Database.Open("StarterSite");
var sql = "UPDATE services SET FileName=#0, FileContent=#1, MimeType=#2 WHERE IDservice=#3";
db1.Execute(sql, fileName, fileContent, fileMime, IDservice);
}
}
And the markup should look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Service</title>
</head>
<body>
<form method="post">
<fieldset>
<legend>Service Information</legend>
<p><label for="fileName">FileName:</label>
<input type="text" name="fileName" value="#fileName" /></p>
<p><label for="fileContent">File Content:</label>
<input type="text" name="fileContent" value="#fileContent" /></p>
<p><label for="fileMime">Mime:</label>
<input type="text" name="fileMime" value="#fileMime" /></p>
<input type="hidden" name="IDservice" value="#IDservice" />
<p> <button type="submit" name="action" value="insert Registered">Uložit</button></p>
</fieldset>
</form>
</body>
</html>
And here's a working sample.
Here's a set of tutorials which, I believe, should be very helpful!

Put your database logic into a controller action, like this:
public class HomeController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// Do database update logic here
// Upon successfully updating the database redirect to a view
// that displays the information, read-only version not editable
return RedirectToAction("Index");
}
catch(Exception ex)
{
// If something went wrong, then re-display the view
// the user tried to update database from
return View();
}
}
}
Now in your view create a form by using the HTML helper Html.BeginForm(), like this:
#using (Html.BeginForm("ActionMethodName","ControllerName"))
{
... your input, labels, textboxes and other html controls go here
<input class="button" id="submit" type="submit" value="Uložit" />
}
Note: Html.BeginForm() will take everything inside of it and submit that as the form data to the controller action specified as parameters to it.

Related

the form Http POST doesn't work, only Get work in asp core mvc

I have a Form that should pass data through POST request, but GET request is being used without passing the data and do model binding of asp core, so buz of that the method Registrationp is never reach if the attribute [HttpPost] is in place ;( .
I tried many ways to get over this problem but none if them worked, even though the other forms post the data and bind the model successfully
HTML:
#model Student_Training.Models.File;
<form method="post" asp-controller="Students" asp-action="Registrationp" enctype="multipart/form-data">
<label asp-for="FileRep" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input type="file" asp-for="FileRep" name="img" accept="image/*" class="form-control custom-file-input" />
<label class="custom-file-label"> Upload...</label>
</div>
</div>
<div class="form-group">
<button id="Button" type="submit" name="submit" formmethod="post" class="btn btn-secondary btn-sm">
<a asp-action="Registrationp"> Save </a>
</button>
</div>
</form>
Controller POST method:
[HttpPost]
public async Task<IActionResult> Registrationp([Bind("FileId, FileName, OwnerId, FileRep")] Student_Training.Models.File imgFileModel, IFormFile img, int? id)
{
var user = await _userManager.FindByNameAsync(User.Identity.Name);
var userEmail = user.Email;
Student Student = _context.Student.FirstOrDefaultAsync(x => x.Email == userEmail).Result;
// StudentId
id = Student.StudentId;
// Save img to wwwroot/img folder
string wwwRootPath = _hostEnvironment.WebRootPath;
Student_Training.Models.File myFile = new Student_Training.Models.File();
string fileName = Path.GetFileNameWithoutExtension(imgFileModel.FileRep.FileName);
string extention = Path.GetExtension(imgFileModel.FileRep.FileName);
imgFileModel.FileName = fileName = fileName + DateTime.Now.ToString("yymmss") + extention;
string path = Path.Combine(wwwRootPath + "/img/", fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
await imgFileModel.FileRep.CopyToAsync(fileStream);
}
// insert recorod to Db
_context.Add(imgFileModel);
await _context.SaveChangesAsync();
return View();
}
As a matter of fact you are using an ancor tag to submit your form, not a submit button. An ancor tag is always generates a GET request. So just remove it from your code:
<button id="submitButton" type="submit" class="btn btn-secondary btn-sm">Save</button>

call mvc controller without post back mvc 5 angularjs

i am creating an asp.net mvc 5 web app(with angularjs)
in my app i am calling a controller to download user pic but the whole page is being refreshed,
and i don't want to postback the particular page
this is how my controller looks
[HttpPost]
public ActionResult profilecompletion(FormCollection fc, HttpPostedFileBase file)
{
// tbl_details tbl = new tbl_details();
var allowedExtensions = new[] {
".Jpg", ".png", ".jpg", "jpeg",".doc",".docx",".pdf",".xlsx",".xls"
};
string id = fc["name"].ToString();
//tbl.Id = fc["Id"].ToString();
//tbl.Image_url = file.ToString(); //getting complete url
//tbl.Name = fc["Name"].ToString();
if (file==null)
{
}
else
{
var fileName = Path.GetFileName(file.FileName); //getting only file name(ex-ganesh.jpg)
var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
if (allowedExtensions.Contains(ext)) //check what type of extension
{
string name = Path.GetFileName(id + fileName); //getting file name without extension
//string myfile = name + "_" + "" + ext; //appending the name with id
// store the file inside ~/project folder(Img)
if (!Directory.Exists(Server.MapPath("~/userpic")))
{
Directory.CreateDirectory(Server.MapPath("~/userpic"));
}
var path = Path.Combine(Server.MapPath("~/userpic"), name);
//tbl.Image_url = path;
//obj.tbl_details.Add(tbl);
//obj.SaveChanges();
file.SaveAs(path);
}
else
{
ViewBag.message = "Please choose only Image file";
}
}
return RedirectToAction("Dashboard", "Dashboard");
}
and this is my cshtml page
#using (Html.BeginForm("profilecompletion", "user", FormMethod.Post, new
{
enctype = "multipart/form-data"
}))
{
<div class="row">
<div class="col-sm-8">
<span>Profile Pic</span>
<input id="imagepath" type="file" file-model="profileimage" ng-text-change="changeimage()" name="file" />
</div>
<div class="col-sm-4">
<img id="myImg" src="#" alt="Choose image" style="height:100px; width:100px; border-radius:10px;" ng-hide="hidestat" ng-src="{{image}}" />
#*<input id="imagepath" type="file" file-model="profileimage" class="form-control" />*#
</div>
</div>
<div class="button-container">
<input type="submit" name="Update" class="btn btn-primary" ng-click="update()" title="save" />
</div>
}
the page load is preventing the app to execute update() function properly
what i need to do here to prevent any kind of postback or pageload without effecting any programmability.
The reason why the page reloads is because you are using a submit button which as its name suggests submits the form with a full postback to the server. You could use a regular button instead:
<input type="button" name="Update" class="btn btn-primary" ng-click="update()" title="save" />
Try this
<button type="button" name="Update" class="btn btn-primary" ng-click="update()" title="save" > Submit </button>

Forward and pass data along in Asp.net

In Asp.net Entity Framework I need to forward to another page and pass some data processed by the second page along.
In PHP I could do something like
<!-- page1.php -->
<form action="page2.php" method="POST">
<input type="hidden" name="id" />
<input type="submit" value="Go to page 2" />
</form>
<!-- page2.php -->
<?php
echo $_POST['id'];
?>
How can this be implemented in Asp.net?
Edit: There is a simple solution using Javascript and jQuery.
<!-- on page 1 -->
$('input[type=submit]').on('click', function (e) {
// Forward to browsing page and pass id in URL
e.preventDefault();
var id= $('input[name=id]').val();
if ("" == id)
return;
window.location.href = "#Request.Url.OriginalString/page2?id=" + id;
});
<!-- on page 2 -->
alert("#Request.QueryString["id"]");
There are, at least, two options:
Session state, like this:
Putting data into Session (your first page)
Session["Id"] = HiddenFieldId.Value;
Getting data out of Session (your second page)
// First check to see if value is still in session cache
if(Session["Id"] != null)
{
int id = Convert.ToInt32(Session["Id"]);
}
Query string, like this:
Putting the value into the URL for the second page as a query string
http://YOUR_APP/Page2.aspx?id=7
Reading the query string in the second page
int id = Request.QueryString["id"]; // value will be 7 in this example
There's a lot of ways to do this, take a look at this link for some guidance.
HTML page:
<form method="post" action="Page2.aspx" id="form1" name="form1">
<input id="id" name="id" type="hidden" value='test' />
<input type="submit" value="click" />
</form>
Code in Page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string value = Request["id"];
}
MVC would look like...
#using (Html.BeginForm("page2", "controllername", FormMethod.Post))
{
#Html.Hidden(f => f.id)
<input type="submit" value="click" />
}
also, read through these MVC tutorials, you shouldn't blindly translate what you know in PHP to ASP.NET MVC, since you need to learn the MVC pattern too.
You can also use <form> with method="POST" in ASP.NET. And get value in code:
int id = int.Parse(Request.Form["id"]);

How to add Paypal buy buttons to items in aspx page?

I am a newbie to paypal. I got a sandbox test item onpaypal and created an
item Buy button which is embedded html code.
Now whenever I insert the html code in the aspx page, it dosen't redirect to the paypal site.
Maybe because of the form tag that covers the html code. Here is the code for paypal buy button for an item:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="3GWR6RV47BCVE">
<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
I tried this code in a plain HTML file, and it worked. But as soon as I put it in a form runat server tag on aspx, it redirects the page to itself.
The problem is that ASP.NET pages define a form within which all the controls are placed (especially if you are using a master page) and HTML does not allow nested form tags.
There are several ways around this including using a normal ASP image button as described here.
You can also use an anchor link as described in this blog. However as noted by the author, the user can save the page source, edit it (e.g. change the price) and then reload it and click the link.
In fact any method that stores the information in the source of the webpage has potential to be abused. Therefore the approach I like, is to use a combination of an ASP image button and the anchor link approach but to implement this on the sever within the button click event:
1) In your ASP page define an image button where you want the PayPal button to go. You can set the ImageURL to the preferred button type provided by PayPal.
<asp:ImageButton
ID="PayPalBtn"
runat="server"
ImageUrl="https://www.paypalobjects.com/en_GB/i/btn/btn_buynow_LG.gif"
onclick="PayPalBtn_Click" />
2) Use the Click event of the button to generate the required information on the server side and then redirect the browser to the PayPal site.
protected void PayPalBtn_Click(object sender, ImageClickEventArgs e)
{
string business = "<insert your paypal email or merchant id here>";
string itemName = "<insert the item name here>";
double itemAmount = 123.451;
string currencyCode = "GBP";
StringBuilder ppHref = new StringBuilder();
ppHref.Append("https://www.paypal.com/cgi-bin/webscr?cmd=_xclick");
ppHref.Append("&business=" + business);
ppHref.Append("&item_name=" + itemName);
ppHref.Append("&amount=" + itemAmount.ToString("#.00"));
ppHref.Append("&currency_code=" + currencyCode);
Response.Redirect(ppHref.ToString(), true);
}
Disclaimer: It may still be possible for users to abuse this approach (although it is now a bit harder) so it is always best to check what has been paid before dispatching goods.
An ASPX page is like a giant HTML form. You need to close the ASPX form before the PayPal button code starts.
Like this:
<form name="default.aspx">
-- Page content
</form>
<!-- Close the form-->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
-- button code
You can also try creating the button as a URL and hyperlink to some text or an image on your site - you can still use the PayPal button image. When you're viewing the button code within PayPal there should be a tab above it labeled "E-mail". Click that and you'll get a URL - if you're creating buttons with a drop-down menu or text field you cannot turn the button into a URL.
This is a hack way of doing it, but before the paypal code enter a closing form tag (This will close the asp pages form) then remove the closing form tag from the paypal code and allow the end of .net page end form tag to close the paypals form..
I did it using an iframe for each button
<iframe height="27" marginheight="0" src="/PayPalButton.htm?button_id=ABCXYZSSSSS" frameborder="0" width="120" marginwidth="0" scrolling="no"></iframe>
Here is the code inside PayPalButton.htm
<html>
<head>
<title>PayPal</title>
<script type = "text/javascript">
// function to get url parameter
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
// function to get button ID from url
function payPalButtonCode() {
var code = '<input value="_s-xclick" type="hidden" name="cmd" /> <input value="';
code = code + getURLParameters('button_id');
code = code + '" type="hidden" name="hosted_button_id" /> '
document.write(code);
}
function payPalButtonQuantity() {
var button_quantity_low = getURLParameters('button_quantity_low');
var button_quantity_high = getURLParameters('button_quantity_high');
var button_quantity_unit = getURLParameters('button_quantity_unit');
var button_quantity_units = getURLParameters('button_quantity_units');
var code = '';
var i;
if (button_quantity_low != 'No Parameters Found')
{
code = '<select name="quantity">';
for ( i = button_quantity_low; i <= button_quantity_high; i++) {
if (i > 1) {
code = code + String.format('<option value="{0}">{0} {1}</option>', i, button_quantity_units);
}
else {
code = code + String.format('<option value="{0}">{0} {1}</option>', i, button_quantity_unit);
}
}
code = code + '</select>';
}
else
{
code = '';
}
document.write(code);
}
function payPalButtonType() {
var code = '<input alt="PayPal – The safer, easier way to pay online." src="';
var button_type = getURLParameters('button_type');
if (button_type=='buy_now'){
code = code + 'https://www.paypalobjects.com/en_GB/i/btn/btn_buynow_LG.gif" type="image" name="submit" />';
}
else
{
//code = code + 'https://www.paypalobjects.com/en_GB/i/btn/btn_subscribe_SM.gif" type="image" name="submit" />';
code = code + 'https://www.paypalobjects.com/en_GB/i/btn/btn_buynow_LG.gif" type="image" name="submit" />';
}
document.write(code);
}
String.format = function() {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
</script>
</head>
<body>
<form id="f1" method="post" action="https://www.paypal.com/cgi-bin/webscr" target="_top">
<script type="text/javascript">payPalButtonCode();</script>
<script type="text/javascript">payPalButtonQuantity();</script>
<script type="text/javascript">payPalButtonType();</script>
<img alt="" style="border: 0px solid;" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" />
</form>
</body>
</html>
For fixed-price buttons, there's a VERY easy, html-only workaround. Just copy the email-link provided by paypal, and create a very normal link using <a> ... </a>, which as content has the image that would normally appear in the <form> statement:
<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3GWR6RV47BCVE" target="_top">
<img src="https://www.paypalobjects.com/it_IT/IT/i/btn/btn_buynowCC_LG.gif" border="0" title="submit" alt="PayPal – The safer, easier way to pay online." />
</a>
I've been searching for a solution today, so even if this thread hasn't been active lately, maybe this can be useful to someone else who wants to avoid code-behind.

asp.net javascript to db

have been struggling with this. Tried everything I can think of. Im using javascript to pass data to db, works fine with ints on another page but now with strings it wont work :s
#using (Html.BeginForm(null, null, FormMethod.Post, new{#id="manageForm"}))
{
#Html.AntiForgeryToken()
<span class="actions">
#T(User.Id.ToString()) #T(" ") #T(ViewData["Tag"].ToString())
<input type="hidden" name="tag" value="fr" />
<input type="hidden" name="id" value="3" />
#T("Follow")
</span>
}
Javascript
<script type="text/javascript">
function followTag() {
$('#manageForm').attr('action', '#(Url.Action("FollowTag"))').submit();
return false;
}
</script>
Controller
[RequireAuthorization]
[HttpPost]
public ActionResult FollowTag(int id, string tag)
{
_service.FollowTag(id, tag);
return RedirectToAction("TagPage","Detail", new
{
});
}
Data Access
public void FollowTag(int id, string tag)
{
DbCommand comm = GetCommand("SPTagFollow");
//user id
comm.AddParameter<int>(this.Factory, "id", id);
//id to follow
comm.AddParameter<string>(this.Factory, "tag", tag);
comm.SafeExecuteNonQuery();
}
route is setup fine and sql(stored procedure) executes perfect. Hopefully one of you can see something obvious
cheers
I think is a problem of mistyping, check your last <a> tag, you typed following.() in the onclick event, see that your javascript function is called followTag.
If that doesn't fix it, then get rid of that foolowTag function, you can specify the action and the controller in the form itself, like this:
#using (Html.BeginForm("FollowTag", "YourControllerName", FormMethod.Post)) {
...
//Delete this line
//#T("Follow")
//This submit button will do the job
<input type='submit' value='#T("Follow")' />
}
That should do it. If you are using the anchor tag just for styling that's ok, otherwise you should use the other way, I think is clearer and besides it takes advantage of razor's great features.

Resources