Partial view was not found - ajax

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...

Related

how i make a condition with ajax and asp mvc

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

Getting Error in codeigniter ajax dropdown changing

Getting Error in codeigniter ajax dropdown changing
[![enter image description here][1]][1]
function fun1(sid) {
//alert(sid);
var obj;
if (window.XMLHttpRequest) {
obj = new XMLHttpRequest();
} else {
obj = new ActiveXObject("Microsoft.XMLHTTP")
}
obj.open("post", "https://99shopin.com/register/getcity?val=" + sid, true);
obj.send();
obj.onreadystatechange = function() {
if (obj.readyState == 4) {
document.getElementById('div1').innerHTML = obj.responseText;
} else {
document.getElementById('div1').innerHTML = "";
}
}
}
Try this, and check Is there still an error?
function fun1(sid){
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('register/getcity'); ?>",
data: ({val: sid}),
//dataType: "json",
success: function (data) {
document.getElementById('div1').innerHTML = data.responseText;
}
});
}

NullReferenceException showing for ValidateAntiForgeryToken in MVC 5

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

Passing AJAX request in MVC3 environment

I was using MVC3 with AJAX. I was using AJAX within another AJAX. For the first AJAX request, it properly sends to the controller with data. But after returning from the AJAX request, I again posting the same data to another action. But second time the data comes null when coming to the controller. Please help me to fix this issue.
Code
$(document).ready(function () {
$('.deleteitems').live('click', function (e) {
var items = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items.push($(this).attr("Id"));
});
var json = JSON.stringify(items);
var perm = $("#Permission").val();
if (items.length != 0) {
if (perm == "True") {
$.ajax({
url: '/ItemControl/ItemControl/Catalogue_Check',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data == "S") {
DelBibsAlso();
}
else {
DelItemsonly();
}
}
});
}
else {
$("#divMes").removeClass("Success");
$("#divMes").addClass("Error");
showError("Sorry you dont have Permission!");
}
}
else {
alert("Select any Items to delete");
e.preventDefault();
}
});
});
function DelItemsonly() {
var items2 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items2.push($(this).attr("Id"));
});
var itemjson = JSON.stringify(items2);
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": itemjson, "DelBib": 0 },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
function DelBibsAlso() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
var bibjson = JSON.stringify(items1);
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": bibjson, "DelBib": cond },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
Controller Code
public ActionResult Catalogue_Check(string[] id)
{
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
var Matched_BibID = (from asd in Db.Items
where ints.Contains(asd.Id)
select asd.BibId).ToList();
foreach (var idd in ints)
{
var bibid = (from bib in Db.Items where bib.Id == idd select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
return Json("S", JsonRequestBehavior.AllowGet);
}
}
return Json("N", JsonRequestBehavior.AllowGet);
}
public JsonResult DeleteItems(string[] id, int? DelBib)
{
//var newid = id.Split(',');
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
foreach (var a in id)
{
int sel = Convert.ToInt32(a);
Item item = Db.Items.Single(i => i.Id == sel);
int Sess = Convert.ToInt16(Session["AccId"]);
string AdminName = User.Identity.Name;
bool Exist = Db.RouteOuts.Any(itm => itm.ItemId == item.Id);
if (!Exist)
{
weed.DeleteIt(item, Sess, AdminName);
var bibid = (from bib in Db.Items where bib.Id == item.Id select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
Db.ExecuteStoreCommand("update Bibs set Status= 'D' where Id={0}", item.BibId);
Db.SaveChanges();
}
}
}
return Json("S", JsonRequestBehavior.AllowGet);
}
function Test() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
//var bibjson = JSON.stringify(items1); **** Loose this line ****
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ "id": items1, "DelBib": cond }), // **** Items are stringified before posting ****
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});enter code here
}
else {
e.preventDefault();
}

MVC3 and Twitter Bootstrap TypeAhead without plugin

I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

Resources