I've created an AJAX call to send data to a stored procedure. Why isn't it working? - kendo-grid

I will post my code and I'm curious if anyone can see what I am doing wrong here. I've tested the Stored Procedure and that works fine so the break must be somewhere in the Controller or Model. See code below:
VIEW:
function saveCalc() {
var TotCost = $("#totCost").val();
var GPM = $("#CalcAmt").val();
var SP = parseFloat(TotCost / (1 - GPM));
var ID = parseInt($("#ID").val());
debugger;
$.ajax({
url: 'Items/ItemsReport_Update2',
type: "Get",
data: { ID: ID, SP: SP },
success: function () {
CalcDialog.close();
CalcDestroy();
$('#ItemsReportgrid').data('kendoGrid').dataSource.read();
$('#ItemsReportgrid').data('kendoGrid').refresh();
}
});
}
CONTROLLER:
public void ItemsReport_Update2( int ID, double SP)
{
ItemsModel oItemsModel = new ItemsModel();
oItemsModel.UpdateItemsReport2(ID, SP);
}
MODEL:
public void UpdateItemsReport2(int ID, double SP)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("sp_UpdateInvItem2", con)
{
CommandType = CommandType.StoredProcedure
};
if (con.State == ConnectionState.Closed)
con.Open();
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#SP", SP);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
}
Thanks in advance for any help. I've run the script with a debugger and it is passing the data correctly.

url: '/Items/ItemsReport_Update2',
You missed '/' in ajax URL

I think your issue is that grid is not populating with the result data
Please change your controller like this if you are loading a kendo grid data
public void ItemsReport_Update2( [DataSourceRequest]DataSourceRequest request,int ID, double SP)
{
//Create a list with your model type
List<> lst = new List<>();
ItemsModel oItemsModel = new ItemsModel();
oItemsModel.UpdateItemsReport2(ID, SP);
DataSourceResult result = lst.ToDataSourceResult(request);
var jsonResult = Json(result,JsonRequestBehavior.AllowGet);
}
then you need to change the javascript like this
function saveCalc() {
var TotCost = $("#totCost").val();
var GPM = $("#CalcAmt").val();
var SP = parseFloat(TotCost / (1 - GPM));
var ID = parseInt($("#ID").val());
var grid = $("#ItemsReportgrid").data('kendoGrid');
debugger;
$.ajax({
url: '/Items/ItemsReport_Update2',
type: "Get",
data: { ID: ID, SP: SP },
success: function (result) {
grid.dataSource.data(result.Data);
CalcDialog.close();
CalcDestroy();
}
});
}

Related

Auto complete ERROR 404 in HTML (using ASP.NET and JQuery)

For some reason in asp.net project, my autocomplete won't work, I have tried different methods from using Data source in data connection but to no avail. I have already created a database for it called Diagnose but for some reason, it displays error 404 on jquery.
Here is my HTML code:
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script>
$(function () {
$("#search-diagnosis").autocomplete({
source: function (request, response) {
var param = {
searchdetails: $('#search-diagnosis').val()
};
$.ajax({
url: "SearchController.cs/GetSearch",
data: JSON.stringify(param),
type: "post",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) { return { value: item } }))
},
});
},
minLength: 1
});
});
</script>
<div class="search">
<input id="search-diagnosis" class="w-75" type="text" placeholder="Start typing your diagnois...">
</div>
Here is CS code:
[WebMethod]
public static List<string> GetSearch(string searchdetails)
{
List<string> search = new List<string>();
string mainconn = ConfigurationManager.ConnectionStrings["mybase.database"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = string.Format("select Name from [dbo].[Diagnose] where Name LIKE '%{0}%'", searchdetails);
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
SqlDataReader sdr = sqlcomm.ExecuteReader();
while (sdr.Read())
{
search.Add(sdr.GetString(0));
}
sqlconn.Close();
return search;
}
It displays error:
When I open the jquery-1.8.0.js:8214 it shows me this xhr.send( ( s.hasContent && s.data ) || null );
I'm stuck at this problem for a while so any help would be great, thanks in advance :D <3
It is returning 404 not found. I think that GetSearch should be inside of an aspx or an ascx file. Webmethod works in System.Web context and in some point it will require Page.

How to extract JSON data received in controller in a String variable

Could you please let me know how to extract JSON data received in a string variable in controller. Please see the attachment.Thanks.
$("#btn1").on("click", function () {
var i = new Array();
var j = 0;
$("#sl1").multiselect("getChecked").map(function () {
alert(this.value);
i.push(this.value);
//i[j] = this.value;
//j++;
}).get();
var postData = { values: i };
jQuery.ajaxSettings.traditional = true;
$.post('/TodoList/searchdata', postData, function (data) {
alert(data.Result);
});
//$.ajax({
// type: "POST",
// url: "/TodoList/searchdata",
// data: postData,
// success: function (data) {
// alert(data.Result);
// },
// dataType: "json",
// traditional: true
//});
});
Controller code:-
public void searchdata(String[] values)
{
//{
// JavaScriptSerializer js = new JavaScriptSerializer();
// List<String[][]> data=js.Deserialize<List<String[][]>>(i);
Console.WriteLine(values);
}
You can use Newtonsoft Json library https://www.nuget.org/packages/Newtonsoft.Json/
So As mentioned in the below link use it like below
string json = #"{ 'Email': 'james#example.com', 'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z', 'Roles': [
'User', 'Admin' ] }";
Account account = JsonConvert.DeserializeObject(json);
if you doesn't have model , just use like below
var model = JsonConvert.DeserializeObject(json);
the check the below link
http://www.newtonsoft.com/json/help/html/deserializeobject.htm
Try this
JavaScriptSerializer js = new JavaScriptSerializer();
var data=js.Deserialize<Dictionary<string, List<string>>>(i);
Use This Class :
public class JsonAttributeClass<T> where T:class ,new()
{
public static string EntityToJsonConvertor(T entity)
{
string json = JsonConvert.SerializeObject(entity);
return json;
}
public static T JsonToEntityConvertor(string json)
{
var entity = JsonConvert.DeserializeObject<T>(json);
return entity;
}
}

Not Able To Parse Web Response Content

I'm trying to retrieve JSON from a URL and read it into my application. I am having an issue when reading the WebResponse. When the response is read, it comes back as only Symbols and is not properly formatted json.
How do I get a properly formatted JSON after streaming my WebResponse?
My Javascript is as follows:
function getJsonWM() {
//var stringedData = JSON.stringify(ajaxData);
$.ajax({
type: "GET",
url: '/Default/GetQuestionByHighestScore',
//data: JSON.stringify("{}"),
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: function (data) {
var label = $("#lblResults");
var json = JSON.stringify(data);
label.text(json);
//if (data.d.Pin == undefined) {
// alert("Error: " + data.d.ErrorMessage);
//} else {
// alert("Please record the following PIN: \r\n \r\n" + data.d.Pin);
//}
},
error: function (data) {
//alert("Error: " + data.d.ErrorMessage);
}
});
}
$(function() {
//$("#btnSubmit").click(getJson);
$("#btnSubmit").click(getJsonWM);
});
My controller is as follows:
public class DefaultController : Controller
{
private const string questionUrl = "https://api.stackexchange.com/2.1/questions?order=desc&sort=activity&site=stackoverflow";
public string GetQuestionByHighestScore()
{
List<Item> list = new List<Item>();
var json = GetJson(questionUrl);
var array = JsonConvert.DeserializeObject<Item>(json);
return list.OrderByDescending(x => x.Score).FirstOrDefault().ToString();
}
public string GetJson(string url)
{
var myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myWebRequest.Method = "GET";
myWebRequest.ContentType = "application/json";
var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
string strResponse = String.Empty;
var encoding = Encoding.Default;
using (var reader = new StreamReader(myWebResponse.GetResponseStream(), encoding))
{
//JavaScriptSerializer js = new JavaScriptSerializer();
strResponse = reader.ReadToEnd();
}
return strResponse;
}
}
My strResponse object is as follows:
"‹\b\0\0\0\0\0\0µ\\\vÛ6¶þ+„\bÚ{G£%Q)‚ÜI“4\t6»iÓtw/”HÙšÑÕä™8Eÿû=‡”ly,y$·iÐ%òóññ¼éßi#ózñô[4|‰wÑe!›ÅÅ\"ßdMÚ¬*ÉEZ,ÿw±(ï\vY-žþ¶¨äzÓð&-‹ÅSÛv/›ZVשX<umæYžÝ¾i¶k¹x\nÝ—iÝÈJ\n`ËãX®›ëŠ7ÐÄØÅb]•IšÉë4çKì½jšuýÔ4Ó˺áñíeš/7Õe\\ææÏôêþß—7ëåóú™í°'Ëg60i½Îøöºà9’¼ÝþÄsÙÅ\"K‹Û–!ðSÜÊ;Y%Yy¯øák³²Yßn+EøûÅ\"­¯yQß«!?MxVË‹Å]*ï¯ãrS40i\a&¢:ìÞ\\,긬`|1¯›k7é]Úl¯…šªM=›:®ãBÏW¯ßd‡¡¶¤R¤Í™­Öô׬™Zih`®CŸfGSmiLµ·Æns\r؃Ï[#^ÉøVVFÝȸ1Š²1jÙMiðÂH\và\\ÄÒ(|Ô}`‘#®û{ÅòçŽ%Q,IË’ü]u'À’\0KÒ”„¤cIÊ[–¿_ìÁ˜oë_3ø’uY7ËJê\ažó/eaÀÞÔ«4iF‘é[¬‡L'p=Ë\n§\"3\bÆ‘y¹¬øo¸¦þhºŒ\a¡—D‚òÀŠBG¸’{^苘E2òe\v[ñ,²hÒ¸,žTÏ>üð$Âñ\aÞ4+m–“ÜÎÐ\\ï(§ ù!­©#v¼a ·MG`\rÄsÁŠ4fšÃFÜIc\rÝÊ*ï#\bs4 wµ565b¸*ïb“G\0„=*ßjZÒ£E´-Q´DÑ ½niûð[o›•’$u\t(nêq!Ø—¥>sN!m\fXÙÊ¿\\–å2“H\nøh\0'jYŒ¼æÅ««7âê­yµû¯÷ùÅ'35~i^_Õ/£[s½*›RËÊ/ˆºc€}¿ªÒšü$y6aíÌÌIá\0鈹gcÌG0qTXj²caÉ|¶°“g°oŒ0\b²PcÁÐÒÂÈ%#DôwµïbN÷¾Ô½¿ù–´ýû(«6ÑÖ#ÆÓ¬NøŒ˜“YkœÀºjÇ¥\\yãû¨f#oL¤IGDÂñ¤ð…å$qB=ϱœ€ZüBo–H“U&\vqS®øtíÜNÉìÓNÀ.˜‚¶ÏÂœZvh\ràÊòèl¹†4æýŠ7µc9¨7C&I§°ŠÆ=ß* É\fÕ0Gí,61ô­7ÑþB½è^ö0øà"
Looks like the server returns gzip encoded response. So make sure that you have set the AutomaticDecompression property when making your HTTP request:
public string GetJson(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
using (var response = (HttpWebResponse)request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string strResponse = reader.ReadToEnd();
return strResponse;
}
}
Also please get rid of those application/json content types. You are making a GET request which doesn't have a body - you are not sending any JSON. Also get rid of the contentType switch in your jQuery AJAX request (same reason).

MVC3 return JSON on error instead of HTML [duplicate]

How do I handle exceptions thrown in a controller when jquery ajax calls an action?
For example, I would like a global javascript code that gets executed on any kind of server exception during an ajax call which displays the exception message if in debug mode or just a normal error message.
On the client side, I will call a function on the ajax error.
On the server side, Do I need to write a custom actionfilter?
If the server sends some status code different than 200, the error callback is executed:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
and to register a global error handler you could use the $.ajaxSetup() method:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
Another way is to use JSON. So you could write a custom action filter on the server which catches exception and transforms them into JSON response:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
and then decorate your controller action with this attribute:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
and finally invoke it:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});
After googling I write a simple Exception handing based on MVC Action Filter:
public class HandleExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
filterContext.Exception.StackTrace
}
};
filterContext.ExceptionHandled = true;
}
else
{
base.OnException(filterContext);
}
}
}
and write in global.ascx:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionAttribute());
}
and then write this script on the layout or Master page:
<script type="text/javascript">
$(document).ajaxError(function (e, jqxhr, settings, exception) {
e.stopPropagation();
if (jqxhr != null)
alert(jqxhr.responseText);
});
</script>
Finally you should turn on custom error.
and then enjoy it :)
Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);
And handle it as standard HTTP error on client as you like.
I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.
I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:
[HttpPut]
public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
{
if (!ModelState.IsValid)
{
return new JsonResult
{
Data = new { ErrorMessage = "Model is not valid", Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
try
{
MyDbContext db = new MyDbContext();
db.Entry(employeToSave).State = EntityState.Modified;
db.SaveChanges();
DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];
if (employeToSave.Id == user.Id)
{
user.Company = employeToSave.Company;
user.Language = employeToSave.Language;
user.Money = employeToSave.Money;
user.CostCenter = employeToSave.CostCenter;
Session["EmployeLoggin"] = user;
}
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
return new JsonResult() { Data = new { Success = true }, };
}
Later in the ajax call I just asked for this property to know if I had an exception:
$.ajax({
url: 'UpdateEmployeeConfig',
type: 'PUT',
data: JSON.stringify(EmployeConfig),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.Success) {
//This is for the example. Please do something prettier for the user, :)
alert('All was really ok');
}
else {
alert('Oups.. we had errors: ' + data.ErrorMessage);
}
},
error: function (request, status, error) {
alert('oh, errors here. The call to the server is not working.')
}
});
Hope this helps. Happy code! :P
In agreement with aleho's response here's a complete example. It works like a charm and is super simple.
Controller code
[HttpGet]
public async Task<ActionResult> ChildItems()
{
var client = TranslationDataHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("childItems);
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
return Json(content, JsonRequestBehavior.AllowGet);
}
else
{
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
}
}
Javascript code in the view
var url = '#Html.Raw(#Url.Action("ChildItems", "WorkflowItemModal")';
$.ajax({
type: "GET",
dataType: "json",
url: url,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Do something with the returned data
},
error: function (xhr, status, error) {
// Handle the error.
}
});
Hope this helps someone else!
For handling errors from ajax calls on the client side, you assign a function to the error option of the ajax call.
To set a default globally, you can use the function described here:
http://api.jquery.com/jQuery.ajaxSetup.

How to pass a JSON object to an action

I have the following jQuery code in a View in MVC3. I want to load a partial view (named OffshoreECore) in a div (#Form) depending on the JSON object passed in the success function. Here's the code:
var inputParamtrs = { 'HeadId': $('#ExpenseId').val(), MProjid': $('#MProjid').val() };
$.ajax({
type: "POST",
url: "/Expenses/Edit",
data: inputParamtrs,
success: function (json) {
('#Form').load('#Url.Action("OffShoreECore", *What comes here ?!?*)');
}
Thanks.
The second parameter of load() is the data which should be sent to the specified URL along with the request. To send your JSON string, try this:
success: function (json) {
$('#Form').load('#Url.Action("OffShoreECore")', json);
}
You example code is also missing a ' delimiter from the second key in inputParamtrs and the $ from the selector in success, but I guess they're just typos.
$.getJSON("/Expenses/Edit",
{
HeadId: $('#ExpenseId').val(),
MProjid: $('#MProjid').val()
},
function (data) {
elementForResult.innerHTML = data;
});
In Controller:
public JsonResult Edit(int HeadId, int MProjid)
{
...
var result = SerializeControl("~/Views/Expenses/Edit.cshtml", null);
return Json(result, JsonRequestBehavior.AllowGet);
}
private string SerializeControl(string controlPath, object model)
{
var control = new RazorView(ControllerContext, controlPath, null, false, null);
ViewData.Model = model;
var writer = new HtmlTextWriter(new StringWriter());
control.Render(new ViewContext(ControllerContext, control, ViewData, TempData, writer), writer);
string value = writer.InnerWriter.ToString();
return value;
}