JQuery Success Function not firing - javascript

I have the following script. It runs, it passes the variables to the controller, the controller executes correctly, but for whatever reason the success function does not fire and therefore does not refresh my html. Instead the error fires off. Nothing is jumping out at me as to the cause. Thanks for the help!
$(function() {
$("#btnUpdateTick").unbind('click').click(function () {
var currenttick =
{
"TicketID":#Html.Raw(Json.Encode(Model.TicketID)),
"Title": $("#Title").val(),
"Creator": $("#Creator").val(),
"StatusID": $("#StatusID").val(),
"Description": $("#Description").val(),
"newComment":$("#txtAddComment").val(),
Cat:
{
"CatID":$("#ddCurrTickCat").val()
}
}
//var newcomment = $("#txtAddComment").val();
var conv = JSON.stringify(currenttick);
$.ajaxSetup({cache:false});
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
});
});
My controller:
[HttpPost]
public PartialViewResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return PartialView("TicketDetails", model);
}

Your controller is returning a view instead of json. You should be returning a JsonResult instead. Try this:
[HttpPost]
public JsonResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return Json(model);
}

If you want to return Partial view from ajax call then modify ur ajax request as :
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "html",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
Now "data" in ur success function will have html returned from PartialViewResult().

Related

ASP.NET MVC call Controller Action with parameter from javascript function

I have web application in ASP.NET MVC C#. I want to call Controller Action method with parameters from javascript but I get always null for parameters.
In .js I have:
$.ajax({
cache: false,
url: this.saveUrl,
type: 'post',
success: this.nextStep,
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
nextStep: function (response) {
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
if (response.redirect) {
ConfirmOrder.isSuccess = true;
location.href = response.redirect;
return;
}
if (response.success) {
ConfirmOrder.isSuccess = true;
window.location = ConfirmOrder.successUrl;
//window.location.href = #Url.Action("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" });
//window.location.href = '#Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" })';
}
Checkout.setStepResponse(response);
}
in RouteProvider.cs I have:
routes.MapLocalizedRoute("CheckoutCompleted",
"checkout/completed/{orderId}/{customerComment}/{customerDate}",
new { controller = "Checkout", action = "Completed", orderId = UrlParameter.Optional, customerComment = UrlParameter.Optional, customerDate = UrlParameter.Optional },
new { orderId = #"\d+", customerComment = #"\w+", customerDate = #"\w+" },
new[] { "Nop.Web.Controllers" });
And finaly in Controller I have:
public virtual ActionResult Completed(int? orderId, string customerComment, string customerDate)
{
//some code here
}
I always get parameters value null and I don't know why. I try to call this Action with parameters on several diferent way like I saw on this forum but no success.
Did you add httpPost wrapper to your controller ?
[HttpPost]
public virtual ActionResult Completed(MyClass MyClassObj )
{
//some code here
}
in your Ajax code u didn't mention your Data type And Data try This Ajax
function Save () {
try {
var req = {
DeliveryCode: value,
}
$.ajax({
url: URL,
type: 'POST',
data: req,
dataType: "json",
async: true,
success: function (result) {
resetLoadWaiting()
},
error: function (e) {
}
});
}
catch (e) {
}
}
Mistake was in url string. Correct one is
ConfirmOrder.successUrl = "http://localhost:8079/checkout/completed/?customerComment=eee&customerEstimateShippingDate=2017-11-14"
I found this solution in this answer: Routing with Multiple Parameters using ASP.NET MVC
I dont need to update RouteProvider with new parameters. It is enough to put in in Controller Action method. Other things happen automatically.

how to submit a form with a local list from javascript

I have a list that i created it in javascript and I want to send it to controller :
function submit1() {
var list_id = [];
var i;
for(i = 0; i < #Model.Count(); i++){
var x =docuzment.getElementsByClassName("bt1")[i].getAttribute("id");
var xxx = document.getElementById(x).style.backgroundColor;
if (xxx == "tomato") {
list_id.push(x);
}
}
$.ajax({
type: "POST",
url: '#Url.Action("add_invitations", "invitations")',
data: {list_id: String},
success: function (data) { alert("SUCCESS"); }
});
}
controller :
public ActionResult add_invitations(List<string> ls )
{
ViewBag.a = ls.Count();
return View();
}
I always get null reference exception for ls>
You are not passing the correct parameter to the action, it expecting to get a parameter named ls, but in your data object you are passing a parameter named list_id.
Try changing it to this:
$.ajax({
type: "POST",
url: '#Url.Action("add_invitations", "invitations")',
data: {ls: list_id},
success: function (data) { alert("SUCCESS"); }
});

how to place a newly created ID into LocalStorage?

I have ran into a predicament. I am passing data to the controller using ajax, and the controller has a method that passes the data to the DAL and the DAL returns an int, that is the newly created ID of the inserted record. My question is how do I get the returned ID and then place it into LocalStorage?
Here is the NewVendorToSubmit
function NewVendorToSubmit() {
var isItChecked;
if ($("#sTaxEnabled").prop("checked")) {
isItChecked = "1";
}
else isItChecked = "0";
var Vendor = {
VendorName: $("#txtVendorName").val(),
Address1: $("#txtVendorAddress1").val(),
Address2: $("#txtVendorAddress2").val(),
City: $("#txtVendorCity").val(),
State: $("#acVendorState").val(),
Zip: $("#txtVendorZip").val(),
VendorPhone: $("#txtVendorPhone").val(),
VendorFax: $("#txtVendorFax").val(),
Email: $("#txtEmail1").val(),
Email2: $("#txtEmail2").val(),
TaxEnabled: isItChecked
};
return Vendor;
}
Here is my jquery function that gets called on the button save event
function SubmitNewVendor() {
var newVendor = NewVendorToSubmit();
$.ajax({
type: "POST",
url: URLParam.AddNewVendor,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(newVendor),
success: function (data, textStatus, jqXHR) { },
complete: function (e) {
ClearVendorFields();
GetVendorGridData();
//CloseTheWindow();
}
})
}
Here is the Controller method that it is calling
[HttpPost]
public int AddVendor(NewVendorToAdd nvta)
{
DAL = new UsherDAL();
int addedVendorID = DAL.AddNewVendor(nvta);
return addedVendorID;
}
and here is the method that is being called from the DAL
public int AddNewVendor(NewVendorToAdd nvta)
{
Vendor vendor = new Vendor();
Address address = new Address();
VendorAddressXREF vendoraddressxref = new VendorAddressXREF();
vendor.VendorName = nvta.VendorName;
int newVendorID = InsertVendor(vendor);
address.Line1 = nvta.Address1;
address.Line2 = nvta.Address2;
address.City = nvta.City;
address.ZipCode = nvta.Zip;
address.StateID = nvta.State;
int newAddressID = InsertAddress(address);
vendoraddressxref.VendorID = newVendorID;
vendoraddressxref.AddressID = newAddressID;
int newVendorAddressXREFID = InsertVendorAddressXREF(vendoraddressxref);
return newVendorID;
}
So how do I go about getting the returned int from AddNewVendor and placing that into LocalStorage, without having to make another round trip to the database?
It seems that the vendor's ID is returned as a response to the POST request, to store it in the local storage you can do this:
$.ajax({
...,
success: function (data, textStatus, jqXHR) {
if(window.localStorage){
localStorage.vendorID = data;
}
},
...
})

Controller not receiver parameter passed by ajax POST in .Net MVC

I want to make an ajax shopping cart, the GetCarts and AddCart all working, but the RemoveRow not
receiver the parameter "strms". When alert(strms) in removeRow(strms) js function, it show right value
of the book id (equal 8). But in the CartController/RemoveRow debug, the strms value is NULL.
I think it's can be a problem with the routing, but I think my route configs are right!
Please help me.
The view is _Layout.cshtml, which contain js code
The controller is CartController
My RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Sach", action = "Detail", id = "7" }
);
routes.MapRoute(
"Cart",
"{controller}/{category}/{ms}/{sl}",
new { controller = "Cart", action = "AddCart", ms = UrlParameter.Optional, sl = UrlParameter.Optional }
);
routes.MapRoute(
"CartRemoveRow",
"{controller}/{action}/{ms}",
new { controller = "Cart", action = "RemoveRow", ms = UrlParameter.Optional });
}
}
CartController.cs
public class CartController : Controller
{
List<CartItem> listCart;
[HttpPost]
public ActionResult GetCarts()
{
listCart = Cart.getCart(Session);
return PartialView("Cart", listCart);
}
public void AddCart(string ms, string sl) {
int masach = int.Parse(ms);
int soluong = int.Parse(sl);
Cart.AddCart(masach, soluong, Session);
//return PartialView("Default");
}
public void RemoveRow(string strms)
{
int ms1 = int.Parse(strms);
var sach = new Sach() { MaSach = ms1 };
Cart.removeCart(sach, true);
}
}
Ajax js code
<script type="text/javascript">
function showCart() {
// alert("1");
//Load content from CartController
$(function () {
//alert("2");
$.ajax({
type: "POST",
url: '#Url.Action("GetCarts", "Cart")',
success: function (data) {
var result = data;
$('#myCart').html(result);
//alert($('#myCart').html());
}
});
});
$("#myCart").modal('show');
}
function addCart(ms, sl) {
var masach = [];
masach.push(ms);
masach.push(sl);
// alert(masach);
$(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("AddCart", "Cart")/'+ms+'/'+ $("#soluong").val(),
success: function (data) {
showCart();
}
});
return false;
});
}
function removeRow(strms){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")/' + strms,
success: function (data) {
showCart();
}
});
});
}
</script>
try passing the parameter in the data property, I have multiple examples but not at home right now.
function removeRow(this_strms){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")',
data: { strms: this_strms},
success: function (data) {
showCart();
}
});
});
}
I normally pass C# objects/classes as parameters like this
public void RemoveRow(CartObject strms)
{
int ms1 = strms.ms1;
var sach = new Sach() { MaSach = ms1 };
Cart.removeCart(sach, true);
}
in JS i do something like this
var thisCartObject= {
ms1: 1,
otherproperty: 0.4,
otherproperty2: "Description"
};
function removeRow(thisCartObject){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")',
data: JSON.stringify({ strms: thisCartObject}),
contentType: 'application/json',
dataType: 'json',
success: function (data) {
showCart();
}
});
});
}
If you are going to try this, try without! your custom route defined in the RegisterRoutes class first.
Rename the javascript variable: "strms" to "ms" and then send it, because in your route "CartRemoveRow" you will receive a variable declared with the name "ms" not "strms".
And of course, in your controller, rename the parameter in the method "RemoveRow" to "ms".
Or more short, change your route to accept "strms":
routes.MapRoute(
"CartRemoveRow",
"{controller}/{action}/{strms}",
new { controller = "Cart", action = "RemoveRow", strms = UrlParameter.Optional });
}

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

Categories

Resources