Save changes function not properly updating the database - javascript

So, I have a button that triggers a javascript function, that calls an AJAX request, that calls an actionresult that should update my database.
Javascript Call
function changeDepartment() {
// Initiate and value variables,
var id = $('#requestId').val();
var user = $('#contactUser').val();
// Bind variables to data object
var data = { id: id }
// Ajax call with data.
$.ajax({
url: '#Url.Action("changeDepartmentActionResult", "ManageRequestResearch")',
type: "POST",
dataType: 'json',
data: data,
success: function (data, textStatus, XmlHttpRequest) {
var name = data.name;
window.location.href = '#Url.Action("Index", "ManageRequestResearch")';
$('#btn-input').val('');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("responseText: " + jqXHR.responseText);
}
});
alert(data);
And then, I have the action result:
[HttpPost]
public ActionResult changeDepartmentActionResult(string id)
{
var moadEntities = new MOADEntities();
moadEntities.Configuration.AutoDetectChangesEnabled = false;
var researchBusiness = new ResearchRequestBusiness(moadEntities);
var request = researchBusiness.FetchRequestById(Convert.ToInt32(id));
var directoryObject = GetActiveDirectoryObject(request.Requestor);
var requstorDisplayName = directoryObject != null ? directoryObject.DisplayName : request.RequestorFullName;
var researchRequestFileBusiness = new ResearchRequestFilesBusiness(moadEntities);
var requestFiles = researchRequestFileBusiness.FetchFilesByRequestId(Convert.ToInt32(id));
var viewModel = new ManageSelectedRequestResearchViewModel()
{
RequestDetails = request,
RequestActivity = request.tbl_ResearchRequestActivity.Select(d => d).ToList(),
Files = requestFiles
};
moadEntities.Configuration.AutoDetectChangesEnabled = false;
if (request.GovernmentEnrollment == true)
{
request.GovernmentEnrollment = false;
request.ManagedCare = true;
moadEntities.SaveChanges();
}
else
{
request.ManagedCare = false;
request.GovernmentEnrollment = true;
moadEntities.SaveChanges();
}
return Json("Status changed successfully", JsonRequestBehavior.AllowGet);
}
From what I have observed, it returns the right record, it makes the changes properly, and it hits the Context.SaveChanges();
when debugging -- i can see before the save changes is made that the values have indeed changed, however--inside the database, no changes are saved.
In addition, i have checked to see that the connection strings are valid.
Any idea what may be causing this?
Thanks ahead of time!

It seems that you are modifying an entity while auto detecting changes are disabled.
If it is intentional then you should inform the context that the entity has been changed.
I assume that MOADEntities is derived from DbContext. So instead of this:
if (request.GovernmentEnrollment == true)
{
request.GovernmentEnrollment = false;
request.ManagedCare = true;
moadEntities.SaveChanges();
}
else
{
request.ManagedCare = false;
request.GovernmentEnrollment = true;
moadEntities.SaveChanges();
}
I would try this:
// Simplify the if..else block
request.ManagedCare = request.GovernmentEnrollment;
request.GovernmentEnrollment = !request.GovernmentEnrollment;
// Notifying the context that the 'request' entity has been modified.
// EntityState enum is under System.Data.Entity namespace
moadEntities.Entry(request).State = EntityState.Modified;
// Now we can save the changes.
moadEntities.SaveChanges();

Related

mvc asp can't update using query from my view

I am trying to have save changes on my script and I just need an update from my table. So far if I clicked the button, the alert success will not pop and can't see any error either. I also tried to verify to my table if the changes is made but the result is nothing happened
Here is the call function from my save button:
<script>
var op = '';
var op_dif = '';
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
alert(op + " " + op_dif); // I can see the value here
$.post("/Home/UpdateOP", {
'data': JSON.stringify([{
'op': op,
'opDiff': Op_dif
}])
}, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
</script>
My view where my update query is located:
public string UpdateOpsDiff(operation[] ops)
{
string res = "";
foreach(var op in ops)
{
string updatetQuery = "update sys.OP_difficulty set op_difficulty = #diff where op = #op;";
MySqlCommand updateCommand = new MySqlCommand(updatetQuery);
updateCommand.Connection = myConnection;
updateCommand.Parameters.AddWithValue("#diff", op.op_dif);
updateCommand.Parameters.AddWithValue("#op", op.op);
myConnection.Open();
int updatedRowNum = 0;
try
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
catch(MySqlException)
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
res = "{status:SUCCESS, updatedRowNum:" + updatedRowNum + "}";
}
return res;
}
Controller where it reads the view query:
public string UpdateOp()
{
string data = Request.Form["data"];
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
return sys.UpdateOpsDiff(rows);
}
catch (JsonSerializationException je)
{
Console.WriteLine(je.Message);
return "{status:'DATA_FORMAT_ERROR'}";
}
}
Is there any missing items that I need. It already working using the query from my controller but this time I need to store my query from my view.
Any suggestions or comments. TIA
Since you're using AJAX callback, you should change return type to ActionResult and mark the action method with [HttpPost] attribute, also you should use return Content() or return Json() depending on returned type from UpdateOpsDiff() (string or object, respectively). Here is an example of proper setup:
[HttpPost]
public ActionResult UpdateOp(string data)
{
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
string result = sys.UpdateOpsDiff(rows);
// return JSON-formatted string should use 'Content()', see https://stackoverflow.com/q/9777731
return Content(result, "application/json");
}
catch (JsonSerializationException je)
{
// do something
return Json(new { status = "DATA_FORMAT_ERROR"});
}
}
Then set the AJAX callback to pass JSON string into action method mentioned above:
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
var values = { op: op, opDiff: op_dif };
$.post("/Home/UpdateOP", { data: JSON.stringify(values) }, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
Note:
The JSON-formatted string should be presented in key-value pairs to be returned as content, as shown in example below:
res = string.Format(#"{""status"": ""SUCCESS"", ""updatedRowNum"": ""{0}""}", updatedRowNum);

Javascript list passing to c#

I have a Asp.net MVC program in which i want to get a list from the View using Javascript and pass that list to the controller. I want to the variables in the list to be string type except for one to be int32.
The problem is the list is either empty or does not pass.
I tried to use stringify but it doesn't fill the requirments.
Here is the code from the javascript part:
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val();
var nodeType = $("#ColumnType").data("kendoComboBox").value();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var ListNodeDetails = JSON.stringify(ListNodedet);
var ListMethod = JSON.stringify(Listmet);
var select = 1;
var url = "/Configuration/CallMethod";
$.get(url, { ListNodeDetails:ListNodeDetails, ListMethod:ListMethod }, function (data) {
$("#Data2").html(data);
});
})
The C# code for the controller were it calls another method in models:
public bool CallMethod(List<Variant> ListNodeDetails, List <string> ListMethod)
{
var AddMethod = RxMUaClient.CallMethod(ListNodeDetails, ListMethod, "127.0.0.1:48030");
return AddMethod;
}
The Model:
public static bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod, string iPAddress)
{
var serverInstance = GetServerInstance(iPAddress);
if (serverInstance == null)
return false;
return serverInstance.CallMethod(ListNodeDetails, ListMethod);
}
The service model
public bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod)
{
try
{
if (_mSession == null)
{
return false;
}
NodeId objectID = NodeId.Parse(ListMethod[0]);
NodeId Methodtype = NodeId.Parse(ListMethod[1]); ;
List<Variant> inputArguments = ListNodeDetails;
List<StatusCode> inputArgumentErrors = null;
List<Variant> outputArguments = null;
StatusCode error = _mSession.Call(
objectID,
Methodtype,
inputArguments,
new RequestSettings() { OperationTimeout = 10000 },
out inputArgumentErrors,
out outputArguments);
if (StatusCode.IsBad(error))
{
Console.Write("Server returned an error while calling method: " + error.ToString());
return false;
}
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
return false;
}
}
At the end it calls some functions using OPC UA to add data.
I have changed it to be ajax function and it works well but only with one list form the lists passed to the method!
I dont know if this is because i read values from kendo box and text box, and they are different types but i tried to stringfy it and it still does not work. On the console both lists are out as strings. So still got a problem with passing the first List "ListNodeDetails"!
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val().toString();
var nodeType = $("#ColumnType").data("kendoComboBox").value().toString();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetails: ListNodedet,
ListMethod: Listmet
};
var url = "/Configuration/CallMethod";
console.log(params); // added sanity check to make sure data is correctly passed
var temp = {
url: "/Configuration/CallMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};
$.ajax(temp);
})

Passing/returning value to/from a function using ajax and callback function

I'm trying to read p_info array returned from the function getproductInfo containing a ajax call but I'm getting undefined value. I'm using a callback function to achieve this but still doesn't work. Where am I wrong?
$(document).ready(function() {
function successCallback(data)
{
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
console.log(product_info); // Correct: shows my product_info array
return product_info;
}
function getProductInfo(prodId, successCallback) {
$.ajax({
type: "POST",
url: "getProductInfo.php",
data: "id=" + prodId,
dataType: "json",
success: function(data) {
var p_info = successCallback(data);
console.log(p_info); // Correct: shows my product_info array
return p_info;
},
error: function()
{
alert("Error getProductInfo()...");
}
});
return p_info; // Wrong: shows "undefined" value
}
var p_info = getProductInfo(12, successCallback);
console.log(p_info); // Wrong: shows an empty value
});
The code should speak for itself. But basically, you cant return an upper-level function inside a function. You must set a variable to be used to return after the ajax is submitted.
//This makes the p_info global scope. So entire DOM (all functions) can use it.
var p_info = '';
//same as you did before
function successCallback(data) {
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
return product_info;
}
//This takes prodID and returns the data.
function getProductInfo(prodId) {
//sets up the link with the data allready in it.
var link = 'getProductInfo.php?id=' + prodId;
//creates a temp variable above the scope of the ajax
var temp = '';
//uses shorthand ajax call
$.post(link, function (data) {
//sets the temp variable to the data
temp = successCallback(data);
});
//returns the data outside the scope of the .post
return temp;
}
//calls on initiates.
var p_info = getProductInfo(12);
console.log(p_info);

MVC- After ajax request Page cannot be refresh

on my view page , i am passing some values to controller by ajax request , on controller action, after checking , redirecting message value to view's controller.Adding message to model and pasisng model to view again with new model value.On second time( postback) model values passed to view as Json but new model value(which is message) cannot be catch by javascript.In my code it is Model.INFO
$.ajax({
type: "POST",
url: '#Url.Action("TeamSaveChanges", "Administrator")',
data: {
ID: '#Model.ID',
doctorID: doctorValue,
nurseID:nurseValue,
driverID:driverValue,
technicianID: technicianValue
},
dataType: "text",
success: function () { alert("#Model.INFO")},
error: function () { alert("Error occured!!!") }
});
Controller
public ActionResult TeamSaveChanges(Guid ID, Guid? doctorID, Guid? nurseID, Guid? driverID, Guid? technicianID)
{
try
{
using (var client = SoapProxyFactory.CreateDSrvGDSoapClient())
{
var emptyTeam = Guid.Empty;
var ambID = client.getAmbulanceIDbyTeamID(ID);
var baseresult = client.checkAmblanceTeamsforDuplicateMembers(ambID, ID);
if (doctorID == emptyTeam && nurseID == emptyTeam && driverID == emptyTeam && technicianID == emptyTeam )
{
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
else
{
foreach (var item in baseresult)
{
if(item.DOCTORCODE == doctorID && item.NURSECODE == nurseID && item.DRIVERCODE == driverID && item.TECHNICIANCODE == technicianID)
throw new Exception("The team with Same Members is exist." + "<p>(" + item.TEAMCODE + ")</p>");
}
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
catch (Exception exp)
{
string message = exp.Message;
return RedirectToAction("TeamMembers", "Administrator", new { ID = ID, message = message });
}
[OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]
public ActionResult TeamMembers(Guid? ID,string message)
{
try
{
if (!ID.HasValue())
return RedirectToAction("Ambulance");
using (var client = SoapProxyFactory.CreateDSrvALLSoapClient())
{
Guid id = ID.Value;
var clientGD = SoapProxyFactory.CreateDSrvGDSoapClient();
var result = client.GetTeamMembers(id);
result.INFO = message;
if (message != null)
{
result.INFO = message;
return Json(result,JsonRequestBehavior.AllowGet);
}
return View(result);
}
}
This line:
success: function () { alert("#Model.INFO")},
Will only pull in the INFO of the model once because it renders the server value in the client. If you are expecting it to change, then you have to pass the result back to success, and accept the new value as such:
success: function (d) { alert(d); },
To return a value to it you have to return from the action:
return Content("SOMEVAL"); // or PartialView or something that is string data
However, redirecting to action isn't going to return a response to the caller, and may not be handled properly through AJAX, so I'm not 100% sure what the question is...
Why would you use AJAX for this? What is happening is your script is firing a request off to your controller, which sends the response back as data, not a redirect to a new webpage.
Just create a form that POSTs those variables to your controller in typical MVC fashion, you'll get the result you want.

JQuery: Calling a webservice

I am developing a SilverLight application wherein on browser close event, i need to do a web service call. I have a web service method which accepts one parameter. When the user clicks on browser close event. I'll be calling the doRelease() function. the releaseuser method requires a parameter usertoken.
I got an error when I'm calling my jQuery function CallService().
Line: 186
Error: Object expected
var varType;
var varUrl;
var varData;
var varContentType;
var varDataType;
var varProcessData;
//Generic function to call AXMX/WCF Service
function CallService() {
$.ajax({
type: varType, //GET or POST or PUT or DELETE verb
url: varUrl, // Location of the service
data: varData, //Data sent to server
contentType: varContentType, // content type sent to server
dataType: varDataType, //Expected data format from server
processdata: varProcessData, //True or False
success: function (msg) {//On Successfull service call
alert("success");
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function Temp(usertoken) {
varType = "POST";
varUrl = "http://localhost/TempWS/MachineHistoryWS.asmx?op=ReleaseUser";
varData = usertoken;
varContentType = "application/json; charset=utf-8";
varDataType = "json";
varProcessData = true;
alert("call service");
CallService();
}
function ServiceSucceeded(result) {//When service call is sucessful
alert("success");
varType = null; varUrl = null; varData = null; varContentType = null; varDataType = null; varProcessData = null;
}
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
varType = null; varUrl = null; varData = null; varContentType = null; varDataType = null; varProcessData = null;
}
function doRelease() {
var usertoken = readCookie("usertoken");
Temp("usertoken");
}
I solved my problem but not using jquery. Here's my solution.
function sendDataAsXML_SOAP() {
var req_params = "", url = "", number = 0, type = "";
/* Configure Parameters */
url = "http://localhost/TempWS/MachineHistoryWS.asmx";
user = "129272802615082804";
req_params = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
req_params = req_params + "<soap:Body><ReleaseUser>";
req_params = req_params + "<credentials>" + user + "</credentials></ReleaseUser></soap:Body></soap:Envelope>";
alert(req_params);
/* Send XML/SOAP Request To Web Service Using Browser's Javascript DOM */
try {
ajax_request = new XMLHttpRequest();
}
catch (trymicrosoft) {
try {
ajax_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (othermicrosoft) {
try {
ajax_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (failed) {
ajax_request = false;
}
}
}
ajax_request.open("POST", url, true);
ajax_request.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
ajax_request.onreadystatechange = receiveXML_SOAPData;
ajax_request.send(req_params);
}
function receiveXML_SOAPData() {
if (ajax_request.readyState == 4) {
if (ajax_request.status == 200) {
alert(ajax_request.responseText);
}
}
}
This looks a little odd:-
function doRelease() {
var usertoken = readCookie("usertoken");
Temp("usertoken");
}
First we assume readCookie is doing the correct thing?
Secondly should that last line be:-
Temp(usertoken);
Third, where is the "Silverlight" angle in all of this?
The data must be wrapped as an object. In CallService function, change:
data: varData,
to:
data: "{input:'" + varData + "'}",
Change "input" to the actual parameter name in your web service method.

Categories