My Ajax Code is
function UserCheck() {
var q = document.getElementById("username").value;
$.ajax({
url: '#Url.Action("Checks","Ajaxx")',
data: {
'userdata': q
},
type: "POST",
dataType: "html",
success: function (data) {
//------------
alert("insuccess");
document.getElementById("username").innerHTML = data.toString();
}
});
}
Am using this ajax code to check whether the entered username is exists
My controller name is Ajaxx and method is checks
Method is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CinemaApplication.Models;
namespace CinemaApplication.Controllers
{
public class AjaxxController : Controller
{
//
// GET: /Ajaxx/
[HttpPost]
public string Checks(string userdata)
{
string tmp = "success";
using (OurDbContext db = new OurDbContext())
{
var SeachData = db.Logins.Where(x => x.username == userdata).FirstOrDefault();
if (SeachData != null)
{
tmp = "Fail";
}
}
return tmp;
}
}
}
This is the whole code of my controller. It is dedicated to this ajax .
the value of username field is correctly arrived in q ,but i don't know that the method (Checks) in controller(Ajaaxx) is working
Try using the following properties in your jquery call:
dataType: 'json',
contentType: "application/json; charset=utf-8"
Ajax code
function Checks()
{
var unm = document.getElementById("username").value;
$.ajax({
type: "POST",
url: "/Ajaxx/Checks",
data: '{user:"' + unm + '"}',
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(result)
{
var mess = $("#Status");
if (result)
{
mess.html('Username available');
mess.css("color", "green");
}
else{
mess.html('Username not available');
mess.css("color", "red");
}
}
});
}
</script>
var mess is holding the id of the span
Controller
[HttpPost]
public JsonResult Checks(string user)
{
bool tmp = true;
using (OurDbContext db = new OurDbContext())
{
var SeachData = db.Logins.Where(x => x.username == user).FirstOrDefault();
if (SeachData != null)
{
tmp = false;
}
}
return Json(tmp);
}
Related
I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?
I have the following javascript using ajax:
function MoveToWeek(weekIndex) {
if (weekIndex == 1) {
var index = #Model.WeekIndex;
index = index+1;
$.ajax({
url: '#Url.Action("RenderCalendar", "Calendar")',
data: { weekIndex: index },
type: "GET",
success: function (data) {
$("#RenderCalendarArea").html(data);
}
});
}
else if (weekIndex == -1) {
var index = #Model.WeekIndex;
index = index+-1;
$.ajax({
url: '#Url.Action("RenderCalendar", "Calendar")',
data: { weekIndex: index},
type: 'GET',
success: function (data) {
$('#RenderCalendarArea').html(data);
}
});
}
}
And the following method in my controller "CalendarController":
[HttpGet]
public ActionResult RenderCalendar(int weekIndex = 0)
{
//..snip
}
I have confirmed the ajax code runs (if I put a javascript breakpoint on the $.ajax line, it'll break there). In addition the values in the ajax method do seem to be set correctly. In the debugger the javascript method has been compiled as such:
function MoveToWeek(weekIndex) {
if (weekIndex == 1) {
var index = 0;
index = index+1;
$.ajax({
url: '/Calendar/RenderCalendar',
data: { weekIndex: index },
type: "GET",
success: function (data) {
$("#RenderCalendarArea").html(data);
}
});
}
else if (weekIndex == -1) {
var index = 0;
index = index+-1;
$.ajax({
url: '/Calendar/RenderCalendar',
data: { weekIndex: index},
type: 'GET',
success: function (data) {
$('#RenderCalendarArea').html(data);
}
});
}
}
However, when this code runs, it does not break inside the method in the controller. Can anyone see why this doesn't work?
This particular partial view didn't use the layout file... which meant it didn't import the jquery lib. That's why it didn't work. Ooops.
I have a weird scenario happens when I send my ajax request that has 2 objects
first time it passes the second obj with the right value while the first object is null.Then second call it passes the first obj with value and the second obj as null
Here's my ajax method
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
And here's my action in controller
public ActionResult EditTask(Task merchTask, string[] items)
{
short CompanyID = Convert.ToInt16((gSessions.GetSessionValue(gSessionsData.Company) as Company).ID);
try
{
merchTask.CompanyID = CompanyID;
if (merchTask.TaskID != 0)
{
taskTemplatesBF.Update(merchTask);
}
else
{
taskTemplatesBF.InsertMerchTask(merchTask);
}
string[] selectedLst = items;
foreach (string item in selectedLst)
{
taskTemplatesBF.InsertItemsLink(CompanyID,merchTask.TaskID,merchTask.ItemCode);
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
ModelState.AddModelError("", ex.InnerException.Message);
}
ModelState.AddModelError("", ex.Message);
}
return RedirectToAction("TasksTemplates", "Merch");
}
*I found a workaround to send each object separately in different ajax
but what's wrong when I send them in one request?
You have added a lot of code in the question but missed the code that was actually needed.
Okay add the event.preventDefault(); and event.stopImmediatePropagation(); functions inside your form summit event as follows:
$(document).ready(function(){
$("formId").on('submit',function(event){
event.preventDefault();
event.stopImmediatePropagation();
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
});
});
Hope this will solve your problem.
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.
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...