How to send static html as an email content in c#? - javascript

I am sending an static html with some dynamic content to user email id using c# and JQuery.
Below is the JavaScriot file from where I am calling th method SendEmail.
$(".EmailInvoice").click(function () {
$.ajax({
type: 'POST',
url: siteUrl + '/invoiceEmail.asmx/SendEmail',
data: JSON.stringify({ }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
},
failure: function (data) {
},
error: function () {
alert("error");
}
});
Below is the invoiceEmail.asmx file
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Web.Services;
using System.Web.Hosting;
namespace meltwish
{
/// <summary>
/// Summary description for invoiceEmail
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class invoiceEmail : System.Web.Services.WebService
{
public static string PopulateBody(string userName, string title, string url, string description)
{
string body = string.Empty;
using (StreamReader reader = new StreamReader(HostingEnvironment.MapPath("~/EmailTemplate.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{UserName}", userName);
body = body.Replace("{Title}", title);
body = body.Replace("{Url}", url);
body = body.Replace("{Description}", description);
return body;
}
public static void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["username"]);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}
//object sender, EventArgs e
[WebMethod]
public static string SendEmail()
{
//string body = this.PopulateBody("John",
string body = PopulateBody("John",
"Fetch multiple values as Key Value pair in ASP.Net AJAX AutoCompleteExtender",
"http://www.aspsnippets.com/Articles/Fetch-multiple-values-as-Key-Value-pair-" +
"in-ASP.Net-AJAX-AutoCompleteExtender.aspx",
"Here Mudassar Ahmed Khan has explained how to fetch multiple column values i.e." +
" ID and Text values in the ASP.Net AJAX Control Toolkit AutocompleteExtender"
+ "and also how to fetch the select text and value server side on postback");
SendHtmlFormattedEmail("wajedkh#gmail.com", "New article published!", body);
//this.SendHtmlFormattedEmail("wajedkh#gmail.com", "New article published!", body);
return "sajjad";
}
}
}
This is the HTMl file that is added to the project. The name is EmailTemplate.html
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<!-- Server CDN Files -- Start -->
<!--<link class="temp" href="http://klcdn.meltwish.com/styles/store/1.0.2/store.css" rel="stylesheet" />-->
<link href="http://localhost:60339/styles/store/1.0.2/store.css" rel="stylesheet" />
</head>
<body>
<img src = "http://www.aspsnippets.com/images/Blue/Logo.png" /><br /><br />
<div style = "border-top:3px solid #22BCE5"> </div>
<span style = "font-family:Arial;font-size:10pt">
Hello <b>{UserName}</b>,<br /><br />
A new article has been published on ASPSnippets.<br /><br />
<a style = "color:#22BCE5" href = "{Url}">{Title}</a><br />
{Description}
<br /><br />
Thanks<br />
ASPSnippets
</span>
</body>
</html>
This i have added in the Web.Config file.
<appSettings>
<add key="Host" value="smtp.gmail.com"/>
<add key="EnableSsl" value="true"/>
<add key="UserName" value="hussainsajjad9991#gmail.com"/>
<add key="Password" value="xxxxx"/>
<add key="Port" value="587"/>
</appSettings>
Actually whenever I have trying to call the javascript ajax method it is going to the error content.
Help me....

Following C# Code Work For me
[System.Web.Services.WebMethod]
public static string SendEmail()
{
using (MailMessage mm = new MailMessage("From", "To"))
{
mm.Subject = "Subject ";
mm.Body = "<html><head></head><body> Content</body></html>";
mm.IsBodyHtml=true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential("From", "password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Timeout = 2000000;
smtp.Send(mm);
return "Success";
}
}
And Use Ajax Code
$.ajax({
type: "POST",
url: siteUrl + '/invoiceEmail.aspx/SendEmail',
data: "{}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (t) { alert(t); },
error: function (t) { alert(t); } })

Related

AJAX call method on another page

I have a list, and when I click a row on that list, I have AJAX syntax that passes an ID to a method in the code behind, and returns the data to some html elements. This works fine, but right now it returns the data to html elements that are on the same page. What if I wanted to have it navigate to another page to display the data? So here is my current code:
My aspx page
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="listPage.aspx.cs" Inherits="listPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Call C# method/function using JQuery Ajax</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#matchupTable tr').click(function () {
var gameID = $(this).attr('id');
//var gameID = '19';
$.ajax({
url: 'listPage.aspx/GetMatchupByID',
method: 'post',
contentType: "application/json",
data: '{gameID:' + gameID + '}',
dataType: "json",
success: function (data) {
$('#awayCity').text(data.d.AwayCity);
$('#awayTeam').text(data.d.AwayTeam);
$('#home').text(data.d.Away);
$('#homeCity').text(data.d.HomeCity);
$('#homeTeam').text(data.d.HomeTeam);
$('#home').text(data.d.Home);
},
error: function (err) {
alert(err);
}
});
});
});
</script>
</head>
<body>
<%-- LIST AREA --%>
<form id="form1" runat="server">
<div>
<table id="matchupTable">
<tr style="cursor: pointer;" id="25"><td>Click me, I won't hurt you</td></tr>
</table>
</div>
</form>
<%-- RESULTS AREA --%>
<div id="awayTeamDiv">
<div id="awayTeamTitle">
<h5 id="awayCity"></h5>
<h3 id="awayTeam"></h3>
<p id="away"></p>
</div>
</div>
<div id="homeTeamDiv">
<div id="homeTeamTitle">
<h5 id="homeCity"></h5>
<h3 id="homeTeam"></h3>
<p id="home"></p>
</div>
</div>
</body>
</html>
My code behind
using System;
using System.Web.Services;
using GamblersDenNet;
using System.Data;
using System.Data.SqlClient;
public partial class listPage: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static Matchup GetMatchupByID(int gameID)
{
Matchup matchup = new Matchup();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TrinoviContext"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("usp_GetMatchupDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#GameID",
Value = gameID
});
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
matchup.GameID = reader["GameID"].ToString();
matchup.Date = reader["Date"].ToString();
matchup.HomeCity = reader["HomeCity"].ToString();
matchup.HomeTeam = reader["HomeTeam"].ToString();
matchup.Home = reader["Home"].ToString();
matchup.AwayCity = reader["AwayCity"].ToString();
matchup.AwayTeam = reader["AwayTeam"].ToString();
matchup.Away = reader["Away"].ToString();
}
return matchup;
}
}
So, if I wanted to instead have a detailsPage.aspx, and when I clicked the tr element, it redirected to this detailsPage.aspx and executed the code, what would that look like? I know I'd have to move my div elements in the RESULTS AREA of my listPage.aspx to the other page, and maybe set that stored procedure to execute on page load, but how would I pass it the parameter from the row I clicked? What would that look like?
In the interest of brevity I removed some extraneous code, so I'm sorry if there may be some syntax errors in my example.
Thanks all!
Try to just make a normal http post request rather than an ajax and have your endpoint GetMatchupByID return a view with your object Matchup as the view model.
See this link for returning a view and passing a view model to it:
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part3#passing-a-viewmodel
My solution to this problem was to use pass the value using a query string:
$('#matchupTable tr').click(function () {
var gameID = '/detailsPage.aspx?gameID=' + $(this).attr('id');
window.location.href = gameID;
});
and then on the Page_Load of detailsPage, I moved the code of GetMatchupByID(), and passed it the parameter by using:
string GameID = Request.QueryString["gameID"];
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TrinoviContext"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("usp_GetMatchupDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#GameID", GameID);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// populate properties I need for display on page
}
con.Close();

Laravel upload image from Javascript given an image URL

I have an image URL in javascript extracted from a canvas in html and i want to create an image from that URL and upload it to my storage files in server.
i can send the Url in a ajax post request to my sendImagetoController function in controller or if there is a method from javascript to do that.My routes are all defined and tested.Please Help
my display.blade.php .
<html>
<head>
<title>HeatMap Display</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src='http://www.patrick-wied.at/static/heatmapjs/assets/js/heatmap.min.js'></script>
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script src="{{ asset('js/jquery.js')}}" type="text/javascript"></script>
<script src="{{ asset('js/app.js') }}" defer></script>
<script src="{{ asset('js/heatmap.js' )}}" type="text/javascript"></script>
<script>
var coordinatesarray = #json($coordinates);
var finalcoordinatesarr=[];
var count=0;
var mapId={{$targetHeatMap->id}};
var mintime=10000000;
var maxtime=0;
var imgUrl="";
coordinatesarray.forEach(element => {
var cor={
'x' : coordinatesarray[count]['x'],
'y' : coordinatesarray[count]['y'],
'value' : coordinatesarray[count]['time_spent']
};
if(mintime>coordinatesarray[count]['time_spent']){
mintime=coordinatesarray[count]['time_spent'];}
if(maxtime<coordinatesarray[count]['time_spent'])
maxtime=coordinatesarray[count]['time_spent'];
finalcoordinatesarr.push(cor);
count++;
});
console.log(finalcoordinatesarr);
function load(){
renderCanvas();
}
function renderCanvas(){
var heatmapInstance = h337.create({
container: document.getElementById('heatMap')
});
var testData = {
min: mintime,
max: maxtime,
data:finalcoordinatesarr
};
heatmapInstance.setData(testData);
imgUrl = (document.getElementById("heatMap").childNodes[0]).toDataURL();
document.getElementById("heatMapPic").src=imgUrl;
}
sendImageToController();
function sendImageToController(){
formdata = new FormData();
if($('#heatMapPic').prop('files').length>0){
file = $('#heatMapPic').prop('files');
formdata.append("heatMapPic",file);
}
formdata.append('tagetHeatMap',$('#targetHeatMap').val());
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: "{{route('HeatMap.moveToStorage')}}",
data: formdata,
type:'post',
// traditional:true,
success:function(response){
console.log("correct");
console.log(response);
},
error:function(e){
console.log("errrooooor");
console.log(e);
},
});
console.log("hi");
}
</script>
</head>
<body onload="load()">
<form id="form" enctype="multipart/form-data">
#csrf
<input type="file" id="heatMapPic" name="heatMapPic" src=""/>
<input type="text" id="targetHeatMap" value="{{$targetHeatMap}}"/>
</form>
<div id="heatMap" style="height:740px"></div>
<a-scene>
{{-- <a-sky radius=10 opacity="0.8" src="{{asset('uploads/heat_map_images/'.$targetHeatMap->heatmap_image)}}"></a-sky> --}}
{{-- <a-sky radius=10 src="{{asset('uploads/'.$imageName)}}"></a-sky> --}}
</a-scene>
</body>
</html>
my Controller method
public function moveToStorage(Request $request){
return 'hello';
}
I use this method in PHP, the fact that the file itself comes to php through the variable $_FILES() and is not visible in the main query.
<?php
putenv("upload_tmp_dir=/var/www/site.com/public_html/upload/");
$uploadDir = getenv("upload_tmp_dir");
$uploadFile = $uploadDir . basename($_FILES['userfile']['name']);
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile);
?>
Then you can open the file in the path in the $uploadFile variable
If you have url which is publicly accessible then you can use it like this
public function moveToStorage(Request $request){
$data = $request->all();
$url = $data['file_url'] ; //file url that you have in javascript
$contents = file_get_contents($url);
$name = substr($url, strrpos($url, '/') + 1);
Storage::put($name, $contents);
return 'hello';
}
OR if your file is posted as base64 then try this
public function moveToStorage(Request $request){
$data = $request->all();
$file = $data['file_url']; //base64 encoded image
$file = substr($file, strpos($file, ",")+1);
$imgeData = base64_decode($file);
$contents = file_get_contents($imgeData);
Storage::put("test.png", $contents);
return 'hello';
}
Looking at your code, it looks like you're trying to send the image before it is actually rendered. You need to move sendImageToController() inside your load function, after renderCanvas().
Also, no need for all the formData stuff. Just send the result of .toDataURL() as-is to the server, then use base64_decode() to turn it back into an image.
Here are the relevant changes:
function load() {
renderCanvas();
sendImageToController(); // send to server AFTER rendering
}
var imgUrl;
function renderCanvas() {
// ...
imgUrl = (document.getElementById("heatMap").childNodes[0]).toDataURL();
// ...
}
Shorter AJAX code:
function sendImageToController() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
$.post("{{route('HeatMap.moveToStorage')}}", {
heatmap: imgUrl // global var set in renderCanvas()!!
})
.done(function(response) {
console.log("correct");
console.log(response);
})
.fail(function(e) {
console.log("errrooooor");
console.log(e);
});
}
On the server, grab the heatmap parameter.
public function moveToStorage(Request $request){
$heatmap = $request->input('heatmap');
$base64 = explode(",", $heatmap)[1];
$binary = base64_decode($base64);
// store $binary data in PNG file
return 'image saved successfully';
}

Spring Controller not returning a html page after an Ajax get Request

So I have a "discount" html page, where a user is prompted to enter a promo code, by using an Ajax GET request from the buttons OnClick, I am able to transfer this promo code to my spring controller, where I manipulate the data appropriately.
For some reason I am unable to "return" a new page from this controller, I do not get any noticeable errors on my server side but on my client side I get this error:
I am not sure if this is related or relevant.
I was wondering is my logic behind this flawed or am I not implementing the correct syntax to return a new page after the AJAX call.
Note: The AJAX request works fine as I am able to get a system.out.print to the console at the bottom of the controller with the relevant info. that I passed.
Here is my html code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></link>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function myFunction(){
var code = document.getElementById("code").value;
var price = document.getElementById("price").value;
$.ajax({
type: "GET",
url: "/calculateDiscount",
data: {
code: code
}, // parameters
contentType: "application/json; charset=utf-8",
datatype: 'json'
//alert(status);
});
}
</script>
</head>
<body>
<div>
<center>
<h3>Total Price: $<text th:text="${totalPrice}" id="price"/> </h3>
<input type="text" name="firstname" id="code">
<button onclick="myFunction()">Calculate Discount</button>
<a style="color:blue" th:href="#{/welcome}">HomeScreen!</a>
<br />
<!-- <a style="color:blue" th:if="${myteam != null}" th:href="#{/leaveteam/{id}(id=${myteam?.id})}">Leave Team?!</a>
-->
</center>
</div>
</body>
</html>
Controller:
#RequestMapping(value="/calculateDiscount", method=RequestMethod.GET)
#ResponseBody
public String CalculateDiscount(Model model, #RequestParam("code") String code, RedirectAttributes redirectAttributes) {
///need to calculate price if codes correct then return page with card info then after proceed call purchasebooks controller!
System.out.println("Price: " + code );
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String email = loggedInUser.getName();
UserLogin user = uR.findByUserName(email);
int totalPrice = 0;
if (code.equals("Discount1010"))
{
Set<Book> books = user.getBooks();
for (Book b : books)
{
totalPrice = totalPrice + b.getPrice();
}
int discountPrice = (int) (totalPrice * .80);
model.addAttribute("totalPrice", totalPrice);
System.out.println("Price: " + discountPrice );
}
else {
Set<Book> books = user.getBooks();
for (Book b : books)
{
totalPrice = totalPrice + b.getPrice();
}
System.out.println("Price: " + totalPrice );
model.addAttribute("totalPrice", totalPrice);
}
return "payment";
}
The page I am trying to return:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<title>Insert title here</title>
</head>
<body>
<h3>Total Price: $<text th:text="${totalPrice}" id="price"/> </h3>
</body>
</html>
Any more info needed let me know.
K.
EDIT: In response to one of the answers below, I do have csrf disabled.
Here is my WebSecurityConfig class:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserLoginRepository userLoginRepository;
//http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
#Autowired
DataSource dataSource;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
http.exceptionHandling().accessDeniedPage("/403");
http.csrf().disable();
//disable csrf to allow communication (we also dont need for this fyp as its not live)
}
#Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/fonts/**", "/images/**", "/css/**");
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select user_name,password,user_status from user_login where user_name=?")
.authoritiesByUsernameQuery("select user_name, password from user_login where user_name=?");
}
#Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
Update: #ResponseBody annotation was added to the controller method, problem still persists
I guess this is CSRF problem. You have Spring Security implemented (I can see
SecurityContexHolder class) and probably csrf enabled - this is default setting. If you want to disable it just use this
Java configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
XML:
<http>
<!-- ... -->
<csrf disabled="true"/>
</http>
But if you want to keep csrf enabled, you need to pass csrf token to ajax header. To do this, include csrf to meta tag:
<head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
And then include csrf to Ajax request:
var token = /*[[${_csrf.token}]]*/ '';
var header = /*[[${_csrf.headerName}]]*/ '';
$(document).ajaxSend(function(e,xhr,options) {
xhr.setRequestHeader(header, token);
});

Ajax.BeginForm with BeforeSend

I have several Ajax.BeginForm on my MVC website. Meanwhile I need to handle the beforeSend event of my Ajax calls.
So the below code works for my manual jquery ajax calls, but it doesn't work with the Ajax.BeginForm helpers:
$.ajaxSetup({
'beforeSend': function (xhr) {
alert('');
}
});
Is there anyway to handle the beforeSend event on the MVC Ajax.BeginForm?
-------------------------------------------EDIT -------------------------------------
I need the before send event since I want to change the request headers :
'beforeSend': function (xhr) {
securityToken = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', securityToken);
}
Thanks
I think you are following samples from http://richiban.wordpress.com/2013/02/06/validating-net-mvc-4-anti-forgery-tokens-in-ajax-requests/ This post does not address the support of Ajax form integration. I did some tests and found the solution.
I assume you use MVC4 with jquery-1.9.1.js, jquery.validate.unobtrusive.js and jquery.unobtrusive-ajax.js referenced.
Following is my code
#model WebApplication1.Models.DummyModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<body>
<div id="Parent">
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "post", OnBegin = "BeginClient" }))
{
#Html.AntiForgeryToken();
<div>First Name</div><div>#Html.TextAreaFor(m => m.FirstName)</div>
<div>Last Name</div><div>#Html.TextAreaFor(m => m.LastName)</div>
<input type="submit" value="Submit" />
}
</div>
<script type="text/javascript">
function BeginClient(xhr) {
alert("posting...");
securityToken = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', securityToken);
}
$.ajaxSetup({
'beforeSend': function (xhr) {
securityToken = $('[name=__RequestVerificationToken]').val();
alert(securityToken);
xhr.setRequestHeader("__RequestVerificationToken", securityToken);
}
});
</script>
</body>
</html>
Basically you need to leverage onBegin event, see http://johnculviner.com/ajax-beginform-ajaxoptions-custom-arguments-for-oncomplete-onsuccess-onfailure-and-onbegin/ there is clear explanation what is the parameters for each event.
Then in your global attribute class, your code looks like
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ValidateAntiForgeryTokenOnAllPostsAttribute : AuthorizeAttribute
{
/// <summary>
/// Executes authorization based on anti-forge token.
/// </summary>
/// <param name="filterContext">MVC pipeline filter context.</param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
// Ajax POSTs and normal form posts have to be treated differently when it comes to validating the AntiForgeryToken
if (request.IsAjaxRequest())
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null
? antiForgeryCookie.Value
: null;
AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
}
else
{
new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
}
}
}
}
By doing this way you can still force to use anti-forgery token with Ajax form.
Hope this helps.
For Ajax.BeginForm you can use AjaxOptions.OnBegin:
#using (Ajax.BeginForm("actionName", "controllerName", new AjaxOptions() {
OnBegin = "requestBeginHandler"})) {
...markup here...
}
Update. To add new request header you can do something like this:
function requestBeginHandler(ajaxContext) {
var request = ajaxCOntext.get_request();
securityToken = $('[name=__RequestVerificationToken]').val();
request.get_headers()['__RequestVerificationToken'] = securityToken;
}

Insert data into database using ajax

I am using ajax to insert data in database
My default .aspx file is as below
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%= btn_Insert.ClientID %>").click(function () {
//var name = $('#<%=txt_name.ClientID%>').val();
//var email=$('#<%=txt_email.ClientID%>').val()
var email = document.getElementById('txt_email').value;
var name = document.getElementById('txt_name').value;
//alert("{'Name':'" + name + "', 'Email':'" + email + "'}");
$.ajax({
type: 'POST',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: "Name=" + name + "&Email=" + email,
//data: $('#form1')
async: true,
success: function (response, data)
{
$('#txt_name').val('');
$('#txt_email').val('');
alert("Record Has been Saved in Database");
alert(response.data.name);
},
error: function () {
console.log('there is some error');
}
});
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
Name : <asp:TextBox ID="txt_name" runat="server" ClientIDMode="Static"></asp:TextBox>
</p>
<p>
E-mail : <asp:TextBox ID="txt_email" runat="server" ClientIDMode="Static"></asp:TextBox>
</p>
<p>
<asp:Button ID="btn_Insert" runat="server" Text="INSERT" OnClick="btn_Insert_Click"/>
</p>
</div>
</form>
</body>
</html>
and my .cs file is as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string Name = Request["Name"];
string Email = Request["Email"];
InsertMethod(Name, Email);
}
SqlCommand cmd;
public Boolean InsertMethod(string Name, string Email)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);
cmd = new SqlCommand("insert into dbo.Demo_AJAX (Name,Email)values (#name,#email)", conn);
cmd.CommandType =CommandType.Text;
cmd.Parameters.AddWithValue("#name",Name);
cmd.Parameters.AddWithValue("#email", Email);
try
{
conn.Open();
//cmd.ExecuteNonQuery();
int affected = cmd.ExecuteNonQuery();
if (affected == 1)
{
//Response.Write("Bhargav");
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
//Response.Write(ex.Message);
return false;
}
finally
{
conn.Close();
}
}
protected void btn_Insert_Click(object sender, EventArgs e)
{
}
}
When I run then it insert one blank data in database.
I don't know how to solve it.
Please any one help me.
Use webmethod then its working.
add namespace
using System.Web.Services;
Change Your Method Like
[WebMethod]
public static Boolean InsertMethod(string Name, string Email)
and remove
<asp:Button ID="btn_Insert" runat="server" Text="INSERT" />
and remove click event from .CS page
then its working.

Categories

Resources