When i am going to update data it alert me a error like "Status = Problem : Fail to Update Client Info". I have run this code without db.Update(ci); code, even without any update code it shows me "Successfully Updated.". But when i am used update method it is not executing. where is the problem i can not defined.... Here is my controller code..
public ActionResult Update(ClientInfo client, string id)
{
//Response.Write("Id : " + id + "<br>");
//Response.Write("Country : " + client.Country + "<br>");
try
{
//if (ModelState.IsValid)
//{
ClientInfo ci = db.Single<ClientInfo>("Where CId=" + id);
if (ci != null)
{
ci.CName = client.CName.ToString();
ci.CCName = client.CCName.ToString();
ci.Address = client.Address.ToString();
ci.PhoneNo = Convert.ToInt32(client.PhoneNo.ToString());
ci.Fax = client.Fax.ToString();
ci.Email = client.Email.ToString();
ci.Country = client.Country.ToString();
ci.PostalCode = Convert.ToInt32(client.PostalCode.ToString());
//ci.Update();
db.Update(ci);
return Json(new { msg = "Successfully Updated."});
}
else
return Json(new { msg = "Fail to Update Client Info." });
//}
//return RedirectToAction("Index");
}
catch
{
return Json(new { msg = "Problem : Fail to Update Client Info." });
}
}
And my script for post data to the server
$('#btnUpdate').click(function () {
var CId = $("#CId").val();
var CName = $("#CName").val();
var CCName = $("#CCName").val();
var PhoneNo = $("#PhoneNo").val();
var Fax = $("#Fax").val();
var Email = $("#Email").val();
var Address = $("#Address").val();
var PostalCode = $("#PostalCode").val();
var Country = $("#Country").val();
var client1 = {
"CId": CId,
"CName": CName,
"CCName": CCName,
"PhoneNo": PhoneNo,
"Fax": Fax,
"Email": Email,
"Address": Address,
"PostalCode": PostalCode,
"Country": Country
};
var lk = "/Clients/Update/" + CId;
//alert("Test : Update " + lk + "\n" + client1.Country);
client = JSON.stringify(client1);
$.ajax({
url: lk,
type: 'POST',
data: client,
dataType: "json",
success: function (data) {
alert("Status = " + data.msg);
},
error: function (data) {
alert("Error = " + data.msg);
}
});
You are not passing your data correctly. Your link is also incorrectly generated. Since you are passing two objects to your view, it's better to specify both in the ajax data object:
var lk = "/Clients/Update/"; // => removed the CId
//alert("Test : Update " + lk + "\n" + client1.Country);
client = JSON.stringify(client1);
$.ajax({
url: lk,
type: 'POST',
data: { client: client, id = CId } // => added an object containing all the expected parameters
dataType: "json",
success: function (data) {
alert("Status = " + data.msg);
},
error: function (data) {
alert("Error = " + data.msg);
}
});
Related
I have a AJAX call for controller as below,
function print(response, endpoint) {
$(".tt").append("<tr><td>" + JSON.stringify(response[0], null) + "</td><td>" + JSON.stringify(response[1], null) + "</td><td>" + JSON.stringify(response[2], null) + "</td><td>" + JSON.stringify(response[3], null) + "</td><td>" + JSON.stringify(endpoint, null) + "</td></tr>");
}
$(".submit").click(function () {
var env = $("#env").find(":selected").text();
var region = $("#region").find(":selected").text();
var country = $("#country").find(":selected").text()
var folderPath = $.trim($('#folderPath').val());
var ajaxRequest = $.ajax({
contentType: "application/json ;charset=utf-8",
type: "GET",
async: false,
url: "/Home/GetmyModel" + "?selcetion=" + env + "®ion=" + region + "&country=" + country + "&folderpath=" + folderPath,
success: function (response) {
if (response != null) {
//print(response, endpoints[i]);
}
},
error: function (exception) {
},
complete: function (data) {
}
});
My controller goes like this
public void GetmyModel(string selcetion, string region, string country, string folderpath)
{
foreach (var item in System.IO.File.ReadLines(folderpath))
{
//do some work with return value as list<string>
//show list<string> in table in view using either print method of JS or by another way
}
}
Everything works fine if i send complete response back by making return type as JsonResult. However i am not understanding how can i print each item.
I'm not understanding why the data is coming back as undefined. It knows there is something there but the value is not being shown. Am I forgetting to do something in the main function? Thanks in advance to whom may solve my dilemma.
Here is the current output I'm getting:
Here is what I need the output to render:
Here is the code for my employee.js:
$(function() {
ajaxCall("Get", "api/employees", "")
.done(function (data) {
buildTable(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
}); // ajaxCall
});
// build initial table
function buildTable(data) {
$("#main").empty();
var bg = false;
employees = data; // copy to global var
div = $("<div id=\"employee\" data-toggle=\"modal\"data-target=\"#myModal\" class=\"row trWhite\">");
div.html("<div class=\"col-lg-12\" id=\"id0\">...Click Here to add</div>");
div.appendTo($("#main"));
$.each(data,function(emp){
var cls = "rowWhite";
bg ? cls = "rowWhite" : cls = "rowLightGray";
bg = !bg;
div = $("<div id=\"" + emp.Id + "\" data-toggle=\"modal\" data-target=\"#myModal\" class=\"row col-lg-12" + cls + "\">");
var empId = emp.Id;
div.html(
"<div class=\"col-xs-4\" id=\"employeetitle" + empId + "\">" + emp.Title + "</div>" +
"<div class=\"col-xs-4\" id=\"employeefname" + empId + "\">" + emp.Firstname + "</div>" +
"<div class=\"col-xs-4\" id=\"emplastname" + empId + "\">" + emp.Lastname + "</div>"
);
div.appendTo($("#main"));
}); // each
} // buildTable
function ajaxCall(type, url, data) {
return $.ajax({// return the promise that '$.ajax' returns
type: type,
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true
});
}
Here is my Controller method code:
// GET api/<controller>
[Route("api/employees")]
public IHttpActionResult Get()
{
try
{
EmployeeViewModel emp = new EmployeeViewModel();
List<EmployeeViewModel> allEmployees = emp.GetAll();
return Ok(allEmployees);
}
catch(Exception ex)
{
return BadRequest("Retrieve failed - " + ex.Message);
}
}
The first parameter of the callback is the index, the value is in the second parameter:
$.each(data,function(index, emp){
i write two functions in jquery client side and c# asp.net server side , i try post json list object to web method but i see error..
jquery code :
function UpdateCart(tableid) {
var page = "Account/Cart.aspx";
var method = "Update_Cart";
var url = "http://" + host + "/" + page + "/" + method;
$(".popup").show();
var cartlist = new Array();
for (var i = 68; i < 71; i++) {
var cart = new Object();
cart.ID = i;
cart.Quantity = 6;
cartlist.push(cart);
}
var jsonArray = JSON.parse(JSON.stringify(cartlist))
$.ajax({
type: "POST",
url: url,
data: jsonArray,
contentType: "application/json; charset=utf-8",
datatype: "json",
async: "true",
success: function (response) {
// success message or do
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject == 1) {
window.location.href = "http://" + host + "/Account/cart";
} else {
$(".errMsg").text("نام کاربری یا رمز اشتباه است");
$(".errMsg").removeClass("alert");
$(".errMsg").addClass("alert alert-danger");
}
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
c# web method :
[WebMethod]
public static string Update_Cart(string[] Carts)
{
if (Carts != null)
{
foreach (var item in Carts)
{
com_Shop_Carts cart = new com_Shop_Carts()
{
Quantity = item.Quantity,
AddDate = DateTime.Now
};
com.shop.ProductManager.Update_Cart(item.ID, cart).ToString();
}
}
return "1";
}
after run i see error 500 and i can't resolve it please give me solution for resolve it.
Apart from this : var jsonArray = JSON.parse(JSON.stringify(cartlist))
Try this : var json={"Carts":cartlist}; then, var jsonArray=JSON.stringify(json);
and remove datatype:json from the ajax call.
Hope this helps.
I am trying to update ClientInfo table. But it is not updating and shows that Undefined. Those code below i have used in my controller for updating my database table data. Where is my problem i cannot find out? experts please help me..
[HttpPost]
public JsonResult Update(ClientInfo clnt, int id)
{
if (ModelState.IsValid)
{
ClientInfo c = db.Query<ClientInfo>("Select * from ClientInfo Where CId=#0", id).First<ClientInfo>();
c.CName = clnt.CName;
c.CCName = clnt.CCName;
c.Address = clnt.Address;
c.PhoneNo = clnt.PhoneNo;
c.Fax = clnt.Fax;
c.Email = clnt.Email;
c.Country = clnt.Country;
c.PostalCode = clnt.PostalCode;
c.Update();
return Json(c, JsonRequestBehavior.AllowGet);
}
else
return Json(new { msg = "Fail to Update Client Info." + id });
}
And Search Controller For searching Data
public JsonResult Search2(string id=null)
{
if (id != null)
{
var sresult = db.Query<ClientInfo>("Where CId=" + id).ToList<ClientInfo>();
return Json(sresult, JsonRequestBehavior.AllowGet);
}
else
return null;
}
And my ajax call from views For searching data by cid value..
#section scripts{
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Styles.Render("~/Content/themes/base/css")
<script type="text/javascript">
$(document).ready(function () {
$('#CId').blur(function () {
var v = $('#CId').val();
var url = "/Clients/Search2/" + v;
// alert("Test : " + url);
$("#CName").val("");
$("#CCName").val("");
$("#PhoneNo").val("");
$("#Fax").val("");
$("#Email").val("");
$("#Address").val("");
$("#PostalCode").val("");
$("#Country").val("");
$.getJSON(url, null, function (data, status) {
$.each(data, function (index, C) {
$("#CName").val(C.CName);
$("#CCName").val(C.CCName);
$("#PhoneNo").val(C.PhoneNo);
$("#Fax").val(C.Fax);
$("#Email").val(C.Email);
$("#Address").val(C.Address);
$("#PostalCode").val(C.PostalCode);
$("#Country").val(C.Country);
});
});
});
For database update i have used this function ...
$('#btnUpdate').click(function () {
var CId = $("#CId").val();
var CName = $("#CName").val();
var CCName = $("#CCName").val();
var PhoneNo = $("#PhoneNo").val();
var Fax = $("#Fax").val();
var Email = $("#Email").val();
var Address = $("#Address").val();
var PostalCode = $("#PostalCode").val();
var Country = $("#Country").val();
var client1 = {
"CId": CId,
"CName": CName,
"CCName": CCName,
"PhoneNo": PhoneNo,
"Fax": Fax,
"Email": Email,
"Address": Address,
"PostalCode": PostalCode,
"Country": Country
};
var lk = "/Clients/Update/" + CId;
//alert("Test : Update " + lk + "\n" + client1.Country);
client = JSON.stringify(client1);
$.ajax({
cashe: false,
async: false,
url: lk,
type: 'POST',
data: client,
dataType: "json",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert(data.msg);
}
});
});
});
</script>
}
If you mean Undefined in your alert message box, it's simple:
$.ajax({
cashe: false,
async: false,
url: lk,
type: 'POST',
data: client,
dataType: "json",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert(data.msg);
}
});
Your ajax code displays the content of data.msg. But when your model is valid, it retrieves the model from the database, updates it and returns the new model. There is no msg json property if it succeeds, hence data.msg is undefined.
If you want it to return a success message, you need to change
return Json(c, JsonRequestBehavior.AllowGet);
into
return Json(new { msg = "Update Successful.", record = c }, JsonRequestBehavior.AllowGet);
then you will have a message in data.msg and your newly updated record in data.record.
DBContext have a save method you must run this.
Did you run Save(); method ?
I have problem in my AjaxHandler.ashx becouse the context.Request["Action"] is null when I send it using JQuery call can someone help me
Note: I'm using html controller not asp,net server controller
<script type="text/javascript">
$(function () {
$("#btnSearch").click(function () {
/*var skill = $("#ddlSkills option:selected").val();
var types = $("#ddlTypes option:selected").val();
var topics = $("#ddlTopics option:selected").val();
var sortBy = $("#ddlSortBy option:selected").val();
*/
$.ajax({
url: "../ideapark/DesktopModules/ResourcesFilter/AjaxHandler.ashx",
contentType: "application/json; charset=uft-8",
type: "POST",
data: $('form').serialize(),
success: function(data) {
for(var i = 0; i < data.length; i++)
{
//t ajax handler recollection of resources.
//U NEED TDESERIALIZE
var resID = data.response[i].ID;
var summary = data.response[i].Summary;
var pageID = data.response[i].PageID;
var name = data.response[i].Name;
var createdOn = data.response[i].CreatedOn
var Total = data.response[i].Total;
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert(errorThrown);
alert(XMLHttpRequest);
alert(textStatus);
console.log(errorThrown);
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
});
});
</script>
/// <summary>
/// Summary description for AjaxHandler
/// </summary>
public class AjaxHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
//context.Response.Write("Hello World");
string response = "";
string var = context.Request["Action"].ToString();
switch (context.Request["Action"])
{
case "ResponseFilterSearch":
response += "{";
Dictionary<string, Object> jsonObject = new Dictionary<string, object>();
string skill = context.Request["Skill"].ToString();
string type = context.Request["Type"].ToString();
string focus = context.Request["focus"].ToString();
string keyword = context.Request["Keyword"];
string sortby = context.Request["SortBy"];
string pageNumber = context.Request["pagenumber"];
SqlDataProvider sqlConn = new SqlDataProvider();
DataSet dsResults = SqlHelper.ExecuteDataset(sqlConn.ConnectionString, "spResourceSearch", skill, type, focus, keyword, sortby, pageNumber);
foreach (System.Data.DataRow row in dsResults.Tables[0].Rows)
{
response += "\"ID\":" + "\"" + row["Id"].ToString() + "\"";
response += "\"Summary\":" + "\"" + row["summary"].ToString() + "\"";
response += "\"PageID\":" + "\"" + row["pageId"].ToString() + "\"";
response += "\"Name\":" + "\"" + row["name"].ToString() + "\"";
response += "\"CreatedOn\":" + "\"" + row["createdOn"].ToString() + "\"";
response += "\"Total\":" + "\"" + row["total"].ToString() + "\"";
}
response += "}";
break;
}
//this returns a json string
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
You seem to be mixing up contentType and dataType.
contentType represents the the content type of the request body(that is the data you're sending to the server), which you've set to json which is not what $('form').serialize() will produce. $('form').serialize() produces data in application/x-www-form-urlencoded which is the default in $.ajax.
Now dataType is the content type of the response body(which is the data you receive from the server) which from your code should be json.
$.ajax({
url: "../ideapark/DesktopModules/ResourcesFilter/AjaxHandler.ashx",
dataType: "json",
type: "POST",
data: $('form').serialize(),
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
....
}
});