I get server error:status of 500 when I try to send 2 parameters to my action in a controller with jquery ajax, dont know why?
this is the jquery code:
$(".genreLinks").click(function () {
var genreId = $(this).attr("name");
var songId = $("#hiddenRank").val();
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyTopTenFavToPlaylist/",
type: "POST",
data: { id: songId, genre: genreId },
success: function (data) {
if (data.status === 1) {
HideAjaxLoader(), ShowMsg("Song Added Successfully")
}
else if (data.status === 4) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data.status === 3) {
HideAjaxLoader(), ShowMsg("Cannot add the song. The song was most likely modified or Deleted, we advise you to refresh the page");
}
else if (data.status === 2) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
controller's action code that accepts two parameters from my request:
[HttpPost]
public ActionResult AddPointAndCopyTopTenFavToPlaylist(int id, int genre)
{
var song = repository.GetTopTenFav(id);
if (song != null)
{
if (!(song.UserName.ToLower() == User.Identity.Name.ToLower()))
{
foreach (var item in song.Points)
{
if (User.Identity.Name.ToLower() == item.UsernameGavePoint.ToLower())
{
return Json(new { status = 2 }, JsonRequestBehavior.AllowGet);
}
}
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = song.Title;
newSong.YoutubeLink = song.YoutubeLink;
newSong.GenreId = genre;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = song.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.TopTenFavId = id;
repository.AddPoint(point);
repository.Save();
return Json(new { status = 1 }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { status = 4 }, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(new { status = 3 }, JsonRequestBehavior.AllowGet);
}
}
I have also registered my new route:
routes.MapRoute(
"AddPoint", // Route name
"{controller}/{action}/{songId},{genreId}", // URL with parameters
new { controller = "Home", action = "", songId = UrlParameter.Optional, genreId = UrlParameter.Optional } // Parameter defaults
);
Related
I want to put a condition if the user want to add a second appointment he receives an alert
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
this is my code in controller :
public JsonResult SaveEvent(Event e)
{
var status = false;
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
status = true;
}
i want to make the user add one time his event and receive an alert i try but not work
I think i can help:
if(Session["appointment"] != "ok")<>
{
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
Session["appointment"] = "ok";
return JSON(new{appointment="ok"});
}
}else
{
return JSON(new {appointment="no-good");
}
and controller:
function SaveEvent(data)
{
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function(data) {
if (data.appointment == "ok")
{
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
else { your msg error here }
},
error: function() {
alert('Failed');
}
})
}
})
dont not forget Session.Clear();
as the user logs out
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));
});
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
I have a problem with an ajax function. I want to send param to method on controller and this ajax function call method twice.
ajax:
$(document).ready(function () {
$(document).on('click', '.exp', function (e) {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
})
$(".exp").click(function() {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
?
<th>
Start date: #Html.TextBox("start_date", null, new { #class = "dateClass start", id = "StartDate" })
End date: #Html.TextBox("end_date", null, new { #class = "dateClass end", id = "EndDate", #data_toggle = "popover", #data_content = "End date should be greater than Start date. ", #title = "Attention" })
#Html.ActionLink("Export Report", "Report_CLeav", "Reports", new { #class = "IndexButton exp", #style = "text-decoration: none;color:white" })
</th>
"Controller"
public class ReportsController : Controller
{
// GET: Export
public ActionResult Index()
{
return View();
}
public void Report_CLeav(DateTime ?start_date, DateTime ? end_date)
{
string path = HttpContext.Server.MapPath("~/App_Data/reports/Report_LeavingCompanyHCT.xlsx");
Models.Report.Report_CompLeav reportcompleav = new Models.Report.Report_CompLeav();
var fileinfo = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(fileinfo))
{
var currentWorksheet = package.Workbook.Worksheets["HC"];
using (var excelToExport = new ExcelPackage())
{
excelToExport.Workbook.Worksheets.Add(currentWorksheet.Name, currentWorksheet);
var workBook = excelToExport.Workbook.Worksheets["HC"];
try
{
workBook = reportcompleav.exportAllEmployeeDataRRecords(workBook,start_date,end_date);
}
catch (Exception e)
{
ViewBag.IsError = true;
}
excelToExport.Save();
Stream stream = excelToExport.Stream;
var memoryStream = stream as MemoryStream;
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats";
Response.AddHeader("Content-Disposition",
"attachment; filename=" + fileinfo.Name);
Response.BinaryWrite(memoryStream.ToArray());
}
}
}
}
}
my controller action:
[HttpPost]
public ActionResult AddPointAndCopyOtherSongToPlaylist(int id)
{
if (CheckIfAddPointToSelf(User.Identity.Name, id))
{
var song = repository.GetSong(id);
foreach (var item in song.Points)
{
if (User.Identity.Name == item.UsernameGavePoint)
{
var data1 = 1;
return Json(new {data1}, JsonRequestBehavior.AllowGet);
}
}
var originalSong = repository.GetSong(id);
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = originalSong.Title;
newSong.YoutubeLink = originalSong.YoutubeLink;
newSong.GenreId = 38;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = originalSong.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.OtherSongId = id;
repository.AddPoint(point);
repository.Save();
int data = 2;
//process here
return Json(new { data }, JsonRequestBehavior.AllowGet);
}
else
{
return null;
}
}
based on different scenarios I want to return a javascript and somehow notify the client of what was returned and based in the result do something in the success part of my ajax call:
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyOtherSongToPlaylist/",
type: "POST",
data: { id: songId },
success: function (data,one) {
if (data && !one) {
HideAjaxLoader(), ShowMsg("Song Added Successfully");
}
else if(!data) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data && one) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
I tried many different variations but I think i need something like data.property1 returned and in the client to check if that property exists or soemthing like that.. please help
You need to return your status code within the object.
return Json( new { data1 = "Some Other Data", status = 1} );
Then in your success handler check data.status.
if (data.status === 1) {
alert(data.data1);
}