Ajax call don't receive html content from MVC Action - javascript

This is my action:
[HttpGet]
public virtual ActionResult DesignItemsList(int dealId, string sort)
{
return View(MVC.Designer.Views._DesignItems, _designerService.GetDesignItems(dealId, sort));
}
The GetDesignItems() method is working correctly.
$(document).ready(function() {
$('.product__filtr__form__select').change(function(e) {
var sort = $(this).val();
var urlFilter = $('#url-filterPanel-hidden-field').val();
var dealId = $('#dealId-hidden-field').val();
var urlItems = $('#url-items-hidden-field').val();
$.ajax({
type: "GET",
data: {
dealId: dealId,
sort: sort
},
url: urlItems,
success: function (result) {
console.log(result);
$('#Product-Items-Container').html(result);
}
});
});
});
Request is working too, but I don't receive the response and get only 500 code.

500 error code means, Internal server error. Your action method failed to process thie request you sent.
Since it is a GET action method, You may add the query string parameters to the url.
var sort = $(this).val();
var dealId = $('#dealId-hidden-field').val();
var urlItems = $('#url-items-hidden-field').val();
urlItems = urlItems+"?dealId="+dealId+"&sort"+sort;
//Let's write to console to verify the url is correct.
console.log(urlItems);
$.get(urlItems,function(res){
console.log('result from server',res);
$('#Product-Items-Container').html(res);
});

Try to replace the view name inside your controller:
return View("YourControllerView", _designerService.GetDesignItems(dealId, sort));
Because I was tested your ajax request and find out that it works fine.
And pay attention to view location. This view must be located inside the directory with the same name as your controller or inside the shared dictory

Related

JQuery/Ajax post in Razor page and redirect to returned view from MVC Action (aka form submitting)

I post a json array to the MVC Action via either JQuery or AJax, and Action handles the request correctly. However, then MVC Action is returning a View and I need to redirect to this View (or replace a body with it) but I don't know how.
So, the action is working well except probably for the returning value:
[HttpPost]
public ActionResult CreateGet(List<string> itemIds)
{
List<TempItem> items = new List<TempItem>();
foreach (string item in itemIds)
{
items.Add(CallApi.Get(Request.Cookies["jwt"], "tempitems", item.ToString()).Content.ReadAsAsync<TempItem>().Result);
}
Invoice inv = new Invoice()
{
IsSupplement = items[0].IsSupplement,
Date = DateTime.Now,
Employee = CallApi.Get(Request.Cookies["jwt"], "employees/getprofile").Content.ReadAsAsync<Employee>().Result,
InvoiceItems = new List<InvoiceItem>()
};
foreach(TempItem item in items)
{
inv.InvoiceItems.Add(new InvoiceItem { Amount = item.Amount, ProductId = item.ProductId, Product = item.Product });
}
return View(inv);
}
And the script inside razor page, that collects selected ids and posts them to the action.
After the post nothing else happens, even the alert is not being called, even though the View page exists and I don't see fails in console.
function CreateInvoice(id) {
var selected = $('#' + id).DataTable().rows('.selected').data();
var items = [];
for (i = 0; i < selected.length; i++) {
items.push(selected[i][0]);
}
var postData = { itemIds: items };
$.ajax({
type: "POST",
url: "/Invoices/CreateGet",
data: postData,
success: function (data) {
alert("success");
window.location.href = data.url;
},
dataType: "json",
traditional: true
});
}
Update
Well, I gave up that nonsense and stuck to GET request that passes array of ids in the URL. I think I just doing things wrong.
You should change ActionResult to JsonResult.
And return like this:
return Json(new {url: "yoururl", inv: yourdata}, JsonRequestBehavior.AllowGet);
If you don't need to do nothing in actual page with data returned from ajax call, you shouldn't use ajax call. You can use submit request and redirect page in backend to new page.

BreezeJs - Ajax Calls with Parameters, No Caching

BreezeJs' POST Ajax calls with parameters that I make to retrieve data are cached by the browser. The "cache: false" attribute does not work, neither does the $.ajaxSetup({ cache: false }); option. How do I prevent it from happening? And if, I need to make GET requests instead, how do I procede? Here is a portion of my code...
JS
var id = 100;
var serviceName = '/breeze/sample';
var ajaxImpl = breeze.config.getAdapterInstance('ajax');
ajaxImpl.ajax({
type: 'POST',
url: serviceName + '/getdata',
data: { dataid: id },
success: function(data) {
// Do something with data
}
});
ApiController
[HttpPost]
[Authorize("User")]
[ActionName("getdata")]
public object GetData(HttpRequestMessage request)
{
if (!IsAuthorized()) // Pre-defined function
throw new HttpResponseException(HttpStatusCode.Unauthorized);
var data = request.Content.ReadAsFormDataAsync().Result;
var dataId = data["dataid"];
var query = "sp_getdata #id"; // Pass parameter #id to stored procedure "sp_getdata"
var id = new SqlParameter("#id", dataId);
return unitOfWork.Context().ExecuteStoreQuery<GetData>(query, id).ToList();
}
Thanks in advance.
We run breeze with GET and POST.
Do you have a Global.asax? Add this to it... not sure if looking for /api/ or /breeze/ would be the only way, but adjust to your circumstances.
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
// Never Cache API (Web API or Breeze.Sharp) Data Requests
if (Request.RawUrl.Contains("/api/") || Request.RawUrl.Contains("/breeze/"))
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}

ASP .NET MVC - Ajax POST action fail

I'm trying to do a simple action with some JavaScript code. I've got some items on a scheduler (DevExpress scheduler component). When I'm double clicking on an appointment (an item then), it should raise an JS function which is the case. My function should get the selected appointment id and pass it to Controller Action. Here is my JS code :
function DoubleClick() {
debugger;
var apt = GetSelectedAppointment(scheduler);
var aptid = apt.appointmentId;
$.ajax({
type: "POST",
url: "/Home/GetAppId",
data: { id: aptid },
dataType: 'json',
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
}
And here is my C# code :
[HttpPost]
public JsonResult GetAppId(int id)
{
context = new SchedulingDataClassesDataContext();
DBAppointment app = (from a in context.DBAppointment where a.UniqueID == id select a).FirstOrDefault();
return Json(new {rep = app});
}
As you can see in my JS code, I'm not doing anything special in case of success. However, I never reach the success part. Plus, when I'm looking at the Chrome dev tool (F12), I'm getting that red error message.
POST http://localhost:25206/Home/GetAppId 500 (Internal Server Error)
Anything that I'm doing wrong?
Man, you need to force things as follows
return Json(new {rep = app},"text/json",JsonRequestBehavior.AllowGet);
In addition, mind your navigation properties (if any) in order to avoid circular reference
According to your error your problem somewhere in select your data from DB or creating anonymous object when you try to serialize it to Json. I rewrite your select to simplify it and not creating any anonymous objects when return it from Controller like this:
[HttpPost]
public JsonResult GetAppId(int id)
{
context = new SchedulingDataClassesDataContext();
DBAppointment app = context.DBAppointment.FirstOrDefault(x => x.UniqueID == id);
return Json(app);
}
Does it work like this?
Please remove the name of the property in ajax data and edit that property as below.
function DoubleClick() {
debugger;
var apt = GetSelectedAppointment(scheduler);
var aptid = apt.appointmentId;
$.ajax({
type: "POST",
url: "/Home/GetAppId",
data: aptid,
dataType: 'json',
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
}
and edit your controller as follows
[HttpPost]
public JsonResult GetAppId([FromBody]int id)
{
//...
}
Please read this blog post which is a good read and allowed me to understand what's going on.
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
The original question that I asked
Simple post to Web Api
Try changing the last line of the method to:
return Json(new { rep = app }, JsonRequestBehavior.AllowGet);
You need to tell C# to allow the json to be returned to the client.

making .ajax request to mvc controller - but .done function never executes

So basically Here is what I do:
in body - onload method I call this javascript function
function TestN() {
var list = new Array();
var allElements = document.getElementsByTagName('*');
$("*[wordNum]").each(function ()
{
var endRes = {
ControllerName: this.id,
WordNumber: this.getAttribute("wordNum")
};
list.push(endRes);
});
jQuery.ajax({
url:' #Url.Action("Translate")' ,
contentType: "application/json",
dataType: "json",
data: { List : JSON.stringify(list) }
,
traditional: true
})
}
what it does - it searches all the controlls with attribute "WrdNum" and then I make an ajax request to the MVC Translate action!
In the Translate Action I make a request to a web service which populates a list of type - TranslateModel
public ActionResult Translate(string List)
{
List<TranslateModel>listto = WebServiceBea.TranslateList(1, List);
return View(listto);
}
Also Here is my TranslateModel
public class TranslateModel
{
public string ControllerName { get; set; }
public string WordNumber { get; set; }
public string Description { get; set; }
}
So basically my question is -> what type should I return to a view - > and how to return this list to a javascript or jquery function which has to set the innerHtml property of some html controls with the record from this list.**
I now that it's strange but that's my task
EDIT
Thanks so much for the help. But now I've got another problem:
After I changed my javascript and put. Done method so I could get the data from the server it looks something like this :
$(document).ready(function () {
var list = new Array();
$("*[wordNum]").each(function () {
var endRes = {
ControllerName: this.id,
WordNumber: this.getAttribute("wordNum")
};
list.push(endRes);
});
jQuery.ajax({
url: ' #Url.Action("Translate")',
contentType: "application/json",
dataType: "json",
data: { List: JSON.stringify(list) }
,
traditional: true,
}).done(function (result)
{
alert ("HII") ;
});
});
no matter what I put in the .done function it never executes. It seems like the controller doesn't know where to return the result. |I| don't now. Can something happen from the fact that I'm making this request from the .layout page - on document ready. s
this looks like a greet place to use knockout js.
here is a great step by step for using knockout with the mvc view
so the method will only return json, the view will not have a model just a call to get the json
if you are going to use $.post to pull your data you could return your list as json
[AcceptVerbs(HttpVerbs.Get|HttpVerbs.Post)]
public ActionResult Translate(string List)
{
List<TranslateModel>listto = WebServiceBea.TranslateList(1, modelObj);
return Json(listto);
}
Looking at what you are posting to the action method, it should already be a list of that type. MVC should do the heavy lifting and transform it to the objects you have.
if however you would like to handle the return yourself you can do something like
jQuery.ajax({
url:' #Url.Action("Translate")' ,
contentType: "application/json",
dataType: "json",
data: { List : JSON.stringify(list) },
traditional: true
}).success(function( returnData, returnStatus)
{
//some code to handle the list of objects reutrned
});
You've already got an answer, but consider the following for cases where you may have controller actions called by javascript:
public ActionResult GetItems(string id)
{
var MyList = db.GetItems(id);//returns a list of items
if (Request.IsAjaxRequest())//called from javascript via AJAX
{
return Json(MyList, JsonRequestBehavior.AllowGet);
}
else //regular hyperlink click
{
return View(MyList);
}
}
To use the list, do the following
$.ajax({url: "'#Url.Content("~/controllername/GetItems")?id=' + id"})
.done(function(result){
var mylist = result.responseText.evalJSON();//this is your list of items
for(i=0;i<mylist .length;i++)
{
var myitem = mylist[i];
}
});
NEVERRRR NEVERRR Forge to put jsonRequestBehavior.AllowGet
Thanks alot for everyone for the help

passing multiple object to controller using ajax in ASP.NET MVC

I work on an ASP.NET MVC project.
I have to pass two parameters to an action in my controller. the first is a serializable object, and the second one is an integer.
First time I tried to pass only one parameter, the serializable object. There is no problem, but when I add the second parameter, the serializable object doesn't delivered (null value), but the integer parameter delivered successfully.
this is my action look like :
[HttpPost]
public bool MyAction(MySerializableObject myData, int intParameter)
{..}
and this is how I try to pass the parameters :
$('#submit-button').click(function () {
var formData = $("#MyForm").serialize();
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, { myData: formData, intParameter: '5005' }, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});
});
Anyone can explain about it ? how can it happens and how to solve the problem ?
thanks.
this may be a bit of a longshot but have you tried swapping the order of the parameters around (IE public bool MyAction(int intParameter, MySerializableObject myData) The reason im asking is that it may be that your client side serialize isnt working quite right.
If not your best bet is to take a look at whats actally getting posted to the server. Open up firebugs net tab or similar in webkit and take a look at whats actually going back to the server.
You could use the following plugin (serializeObject) instead of .serialize:
var formData = $('#MyForm').serializeObject();
// add some data to the request that was not present in the form
formData['intParameter'] = 5005;
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, formData, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});

Categories

Resources