NullReferenceException showing for ValidateAntiForgeryToken in MVC 5 - ajax

I'm trying to save data using ajax in MVC 5. When I'm posting form data without #Html.AntiForgeryToken(), it's working nicely. But it's showing me Object reference not set to an instance of an object error for using #Html.AntiForgeryToken(). Here is my ajax code:
$.ajax({
type: "POST",
url: "/Employees/Create",
data: data,
async: false,
success: function (result) {
if (result == 1) {
window.location.href = '/Employees';
}
else {
$('#error-span').html('Error in insert.');
}
},
error: function () {
alert('Failed');
}
});
Here is my controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Address,JoinDate,DoB,Gender,BloodGroup,Email,LastName,FirstName,Mobile,UpdateDate,UpdatedBy,Status,EmployeeType,CreatedBy,CreateDate,DesignationId")] EmpDetail empDetail)
{
try
{
Regex rgx = new Regex("[^a-zA-Z0-9 - .]");
empDetail.FirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(rgx.Replace(empDetail.FirstName, "").ToLower()).Trim();
empDetail.LastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(rgx.Replace(empDetail.LastName, "").ToLower()).Trim();
empDetail.Email = empDetail.Email.ToLower().Trim();
empDetail.UpdateDate = DateTime.Now;
empDetail.CreatedBy = 234;
empDetail.CreateDate = DateTime.Now;
empDetail.UpdatedBy = 234;
empDetail.Status = 1;
if (ModelState.IsValid)
{
db.EmpDetails.Add(empDetail);
db.SaveChanges();
return Json(1);
}
else
{
return Json(2);
}
}
catch (Exception e)
{
return Json(e.Message);
}
}

This is happening because the data is being sent via JSON instead of HTML Form data. You should try to pass the token in the headers. For example:
View:
<script>
#functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
$.ajax("api/values", {
type: "post",
contentType: "application/json",
data: { }, // JSON data goes here
dataType: "json",
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
</script>
Controller:
void ValidateRequestHeader(HttpRequestMessage request)
{
string cookieToken = "";
string formToken = "";
IEnumerable<string> tokenHeaders;
if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
{
string[] tokens = tokenHeaders.First().Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken);
}
Source: https://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

Related

Post ajax values to MVC Action Result

Ok, so I have the following Ajax get request going to a [HttpPost] controller method in an ASP.NET MVC 5 application.
The javascript function shown here successfully posts the values to the server side:
<script>
function get_row() {
var one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
var two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
var result = one + "," + two;
//var result = {};
//result.one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
//result.two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
if (result != null) {
$.ajax({
type: 'get',
url: "/Manage/CreateGroupRoleRestriction",
//url: '#Url.RouteUrl(new{ action= "CreateGroupRoleRestriction", controller= "Manage", one = "one", two = "two"})',,
data: { one, two },
//params: { one, two }
/*dataType: String,*/
//success: alert(result)
});
}
else {
alert("Error");
}
}
</script>
However, the issue is that the string values will not post to the Action Result, see below.
The values "one" and "two" are null.
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("/Manage/CreateGroupRoleRestriction?{one,two}")]
[ValidateAntiForgeryToken]
public ActionResult CreateGroupRoleRestriction(FormCollection formCollection, string message2, string one, string two)
{
UserDataBusinessLayer userDataBusinessLayer = new UserDataBusinessLayer();
userDataBusinessLayer.Restrict1(message2);
UserDataBusinessLayer userDataBusinessLayer2 = new UserDataBusinessLayer();
userDataBusinessLayer2.Restrict2();
try
{
UserData userData = new UserData();
TryUpdateModel(userData);
if (ModelState.IsValid)
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer3 = new UserDataBusinessLayer();
userDataBusinessLayer3.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
else
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer4 = new UserDataBusinessLayer();
userDataBusinessLayer4.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
}
catch (Exception ex)
{
Logger.Log(ex);
return RedirectToAction("CreateGroupRoleRestriction");
}
}
Please try changing 'type' in ajax to 'post'.
type: 'post'

Session not retaining TempData through multiple Ajax calls to Controller

Im trying to work with an object (VideoInfo) in several Action methods. A form sends a viewmodel with a video file to the Upload method in VideoController. It uploads the video and returns a generated guid. When the callback has returned, a new ajax call is made to the Convert method which returns the guid. As seen in the javascript part of Create.cshtml it makes two other Ajax calls, one to the Progress method and one to the Azure method.
When trying to fetch the VideoInfo object in the Azure method and the Progress method, videoInfo is null. Though it successfully retains the data between the Upload method and Convert method. Im using TempData.Peek() so that it shouldnt mark it for deletion.
I can see that the Upload and Convert method is using the same instance of VideoController, where as the Progress and Azure method uses another instance, I guess this could have to do with the problem.
InstanceId when running Upload method: 23ef96fa-c746-4722-ad07-e9e40fc95f29
InstanceId when running Convert method: 23ef96fa-c746-4722-ad07-e9e40fc95f29
InstanceId when running Progress method: 0aba24b2-ccb8-434d-a27d-cc66cb52c466
InstanceId when running Azure method: 0aba24b2-ccb8-434d-a27d-cc66cb52c466
How can I retain data between my Ajax calls in the VideoController?
Why is the instance id same for the first two calls but then it changes?
VideoController.cs
using System;
namespace MediaPortal.Controllers
{
[Authorize(Roles = "Admin")]
public class VideoController : Controller
{
private static Guid InstanceId { get; }
static VideoController()
{
InstanceId = Guid.NewGuid();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(CreateVideoViewModel model)
{
if (ModelState.IsValid)
{
if (model.File != null)
{
Debug.WriteLine("Upload method InstanceId: " + InstanceId.ToString());
// ...
TempData[videoInfo.Id] = videoInfo;
videoInfo.cvvm.File.SaveAs(videoInfo.TempPath);
return Json(new { Successfull = true, Id = videoInfo.Id });
}
return null;
}
return null;
}
[HttpPost]
public ActionResult Convert(string id)
{
Debug.WriteLine("Convert method InstanceId: " + InstanceId.ToString());
// Create new object of FFMpegConvertor
var converter = new FFMpegConverter();
VideoInfo videoInfo = (VideoInfo)TempData.Peek(id);
// ...
return Json(new { Successfull = true, Id = videoInfo.Id });
}
[HttpPost]
public ActionResult Azure(string id)
{
Debug.WriteLine("Azure method InstanceId: " + InstanceId.ToString());
VideoInfo videoInfo = (VideoInfo)TempData[id];
// ...
if (videoUpload != null && thumbnailUpload != null)
{
Video video = new Video
{
Id = videoInfo.Id.ToString(),
Name = videoInfo.cvvm.Name,
ProjectId = videoInfo.cvvm.ProjectId,
Type = "mp4",
VideoUri = videoUpload.Uri.ToString(),
ThumbnailUri = thumbnailUpload.Uri.ToString()
};
db.Videos.Add(video);
db.SaveChanges();
return Json(new { Successful = true, Data = Url.Action("Index", new { projectId = videoInfo.cvvm.ProjectId }) });
}
return null;
}
[HttpPost]
public JsonResult Progress(string id)
{
Debug.WriteLine("Progress method InstanceId: " + InstanceId.ToString());
try
{
VideoInfo videoInfo = (VideoInfo)TempData.Peek(id);
return Json(new { Data = videoInfo.Progress });
}
catch
{
return Json(new { Data = "No Video Information in Dictionary for Id: " + id });
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Create.cshtml (JQuery/Ajax)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$.noConflict();
jQuery(document).ready(function ($) {
var bar = $('.progress-bar');
var percent = $('.percent');
$('#Myform').ajaxForm({
type: "POST",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function (uploadStatus) {
console.log("Upload finished for video with Id: " + JSON.parse(uploadStatus.responseText).Id);
setTimeout(function () { progress(uploadStatus) }, 1000);
$.ajax({
type: "POST",
url: '#Url.Action("Convert", "Video")?id=' + JSON.parse(uploadStatus.responseText).Id,
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (convertStatus) {
console.log("Conversion finished for video with Id: " + JSON.parse(convertStatus.responseText).Id);
$.ajax({
type: "POST",
url: '#Url.Action("Azure", "Video")?id=' + JSON.parse(convertStatus.responseText).Id,
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (azureStatus) {
window.location.href = JSON.parse(azureStatus.responseText).Data;
}
});
}
});
}
});
function progress(uploadStatus) {
$.ajax({
type: "POST",
url: '#Url.Action("Progress", "Video")?id=' + JSON.parse(uploadStatus.responseText).Id,
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (progressStatus) {
console.log("Progress: " + JSON.parse(progressStatus.responseText).Data);
if (JSON.parse(progressStatus.responseText).Data < 100) {
setTimeout(function () { progress(uploadStatus) }, 1000);
}
else if (JSON.parse(progressStatus.responseText).Data >= 100) {
console.log("Video Conversion Completed");
}
else {
console.log("Something went wrong");
}
}
})
}
});
</script>
It seems IIS Express was the problem. I cant say why though. I realized this because when I deployed the project to my production server in Azure it all worked fine.
So instead of using IIS Express I installed IIS on my development machine, works perfectly after that.

ASP.net cascading dropdown list

trying to implement country state dropdown in mvc but couldn't..
conotroller :-
[HttpGet]
public ActionResult GetCities(int StateId)
{
Business.Services.City cityService = new Business.Services.City();
List<Business.Models.City> stateList = cityService.GetCityByStateId(StateId);
//var jsonSerialiser = new JavaScriptSerializer();
//var json = jsonSerialiser.Serialize(stateList);
return Json(new { stateList }, JsonRequestBehavior.AllowGet);
}
method:
public List<Models.City> GetCityByStateId(int StateId)
{
try
{
var list = new List<SelectListItem>();
Collection<DBParameters> parameters = new Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "StateId", DBType = DbType.Int32, Value = StateId });
var city = this.ExecuteProcedure<Models.City>("GetCityByState", parameters).ToList();
//if (city != null && city.Count > 0)
//{
// list = city.Select(x => new SelectListItem { Text = x.CityName, Value = x.StateId.ToString() }).ToList();
//}
return city;
}
catch (Exception ex)
{
throw;
}
}
change event:
$('.ddlstate').change(function () {
debugger;
$.ajax({
url: '#Url.Action("GetCities", "User")',
type: "GET",
data: { StateId: $(this).val() },
dataType: "json",
success: function (result) {
debugger;
//alert(result.stateList[0].CityId);
$.each(result.stateList, function () {
debugger;
$('.cityddl').append($("<option></option>").val(CityId).html(CityName));
});
},
error: function (result, status, jQxhr) {
alert("Error: " + result + "-" + status + "-" + jQxhr);
}
});
});
i get count of the citites in method and controller but when i run project and change state dropdown i got blank city dropdown. what is wrong?
It looks like you're missing a couple of things in the $.each() call.
You should pass the JSON result from the ajax call to the $.each
You also need to provide a parameter to the callback function so that the callback function has something to work with
It could look something like this:
$.each(result.stateList, function(index, city) {
$('.cityddl').append($("<option></option>").val(city.CityId).html(city.CityName));
});

Partial view was not found

I have two actions in a controller that are called via ajax:
[HttpPost]
public ActionResult Slider(HttpPostedFileBase file)
{
var imagem = System.Web.HttpContext.Current.Request.Files["SliderImage"];
string path = Global.GetAppSetting("CaminhoImagensSlider");
if(imagem != null && imagem.ContentLength > 0)
{
String caminho = Path.Combine(path, imagem.FileName);
db.ImagensSlider.AddObject(new ImagensSlider()
{
Caminho = caminho
});
db.SaveChanges();
Global.SalvarArquivo(caminho, imagem.InputStream);
}
SliderViewModel sliderViewModel = new SliderViewModel(caminhoImagensSlider);
return PartialView("_ImagensSliderPartial", sliderViewModel.Imagens);
}
[HttpPost]
public ActionResult DeletaImagensSlider(int[] imagens)
{
foreach(int id in imagens)
{
ImagensSlider imagemSlider = db.ImagensSlider.Where(i => i.IdImagem == id).Single();
db.ImagensSlider.DeleteObject(imagemSlider);
db.SaveChanges();
}
SliderViewModel sliderViewModel = new SliderViewModel(caminhoImagensSlider);
return PartialView("_ImagensSliderPartial", sliderViewModel.Imagens);
}
The first action works fine, but the second (DeletaImagensSlider) does not work. Checking the Chrome console I found that error:
The partial view '_ImagensSliderPartial' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Configuracoes/_ImagensSliderPartial.aspx
~/Views/Configuracoes/_ImagensSliderPartial.ascx
~/Views/Shared/_ImagensSliderPartial.aspx
~/Views/Shared/_ImagensSliderPartial.ascx
~/Views/Configuracoes/_ImagensSliderPartial.cshtml
~/Views/Configuracoes/_ImagensSliderPartial.vbhtml
~/Views/Shared/_ImagensSliderPartial.cshtml
~/Views/Shared/_ImagensSliderPartial.vbhtml
EDIT:
JS
$("#formSlides").on("submit", function (e) {
e.preventDefault();
var data = new FormData();
var files = $("#imagem").get(0).files;
if (files.length > 0) {
data.append("SliderImage", files[0]);
}
$.ajax(this.action,
{
type: 'POST',
data: $(this).serialize(),
contentType: false,
processData: false,
data: data,
success: function (result) {
$("#imagensContainer").html(result);
}
});
});
$(document).on('change', '[type=checkbox]', function (e) {
if (this.checked) {
imagensChecadas += 1;
imagens.push(this.id);
}
else {
imagensChecadas -= 1;
imagens.remove(this.id);
}
if (imagensChecadas > 0) {
$("#btnDeleteImages").show();
}
else {
$("#btnDeleteImages").hide();
}
});
$("#btnDeleteImages").on("click", function () {
if (confirm("Tem certeza que deseja deletar estas imagens?")) {
$.ajax("/Configuracoes/DeletaImagensSlider", {
type: 'POST',
data: JSON.stringify(imagens),
contentType: 'application/json',
success: function (result) {
$("#imagensContainer").html(result);
}
});
}
});
Why is this view found in one action but not in the other?
I solve the problem by puting the entire path: "~/Areas/Admin/Views/Shared/_ImagensSliderPartial.cshtml".
But I cant understand why it works in different ways in the two actions...

Ajax post a JSON model to ASP.Net MVC4 with Anti-forgery token

I am submitting json model through ajax post. Its not working after adding user validation.
var token = $('input[name=""__RequestVerificationToken""]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax({
url: '/SalesQuotation/Create',
cache: false,
headers: headers,
data: JSON.stringify(salesquotation),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
async: false,
success: function (result) {
if (result.Success == "1") {
window.location.href = "/SalesQuotation/Create";
}
else {
alert(result.ex);
}
}
});
Controller :
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create(SalesQuotation salesquotation)
{
try
{
if (ModelState.IsValid)
{
if (salesquotation.QuotationId > 0)
{
var CurrentsalesQuotationSUb = db.SalesQuotationSubs.Where(p => p.QuotationId == salesquotation.QuotationId);
foreach (SalesQuotationSub ss in CurrentsalesQuotationSUb)
db.SalesQuotationSubs.Remove(ss);
var CurrentsalesQuotationDta = db.DTATrans.Where(p => p.QuotationId == salesquotation.QuotationId);
foreach (DTATran ss in CurrentsalesQuotationDta)
db.DTATrans.Remove(ss);
foreach (SalesQuotationSub ss in salesquotation.salesquotationsubs)
db.SalesQuotationSubs.Add(ss);
foreach (DTATran ss in salesquotation.dtatrans)
db.DTATrans.Add(ss);
db.Entry(salesquotation).State = EntityState.Modified;
}
else
{
db.SalesQuotations.Add(salesquotation);
}
db.SaveChanges();
}
}
catch (Exception ex)
{
return Json(new { Success = 0, ex = "Unable to save... " + ex.Message.ToString()});
}
return Json(new { Success = 1, ex = new Exception("Saved successfully.").Message.ToString() });
}
View:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<input name="__RequestVerificationToken" type="hidden"
value="H4zpQFvPdmEdGCLsFgeByj0xg+BODBjIMvtSl5anoNaOfX4V69Pt1OvnjIbZuYrpgzWxWHIjbng==" />
The server return
What could be missing in my method. Please advice....
Attribute selectors should only have a single set of quotes around them. Your code has two quotes on each side.
This:
var token = $('input[name=""__RequestVerificationToken""]').val();
should be this:
var token = $('input[name="__RequestVerificationToken"]').val();
Use [ValidateJsonAntiForgeryToken] attribute in action method.

Resources