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.
Related
I am trying to apply a filter to data that is being displayed on a map but for some reason, the Ajax call that I have set up is not being executed. I can reach the console.log line in the view but anything after that in the Ajax call is never executed. This is being done in ASP.NET MVC.
I have similar Ajax calls in this project from other developers that function in a similar manner. I have tried to restructure my code to work in a similar manner, but with no success. The other developers have no idea what is going on either.
C# in the controller
[HttpPost]
public ActionResult MapFilter(string filterLake, bool filterPets)
{
var filteredProperties = db.Properties.Include(a => a.PropertyCategory).Where(b => b.Status == true).Select(x => new { x.PropertyName, x.PropertyId, x.RatePerNight, x.RatePerWeek, x.MarketingTitle, x.Latitude, x.Longitude, x.Pets, x.PropertyCategory.PropertyCategoryName });
if (filterLake != "")
filteredProperties = filteredProperties.Where(a => a.PropertyCategoryName == filterLake);
if (filterPets != true)
filteredProperties = filteredProperties.Where(a => a.Pets == filterPets);
var jsonProperties = JsonConvert.SerializeObject(filteredProperties);
return new JsonResult()
{
Data = jsonProperties,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
JavaScript & Ajax in the View
var filterLake, filterPets;
var btnApplyFilters = document.getElementById("applyFilters");
var filterLakeNode = document.getElementById("filterLake");
var filterPetsNode = document.getElementById("filterPets");
$(document).ready(function () {
btnApplyFilters.onclick = function () {
filterLake = filterLakeNode.options[filterLakeNode.selectedIndex].value;
filterPets = filterPetsNode.options[filterPetsNode.selectedIndex].value;
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
$.ajax({
url: "/Estates/MapFilter",
type: "Post",
data: {
"filterLake": filterLake,
"filterPets": filterPets
},
success: function (result) {
filteredMapData = result;
console.log("Result = " + result);
loadMapMarkers(true)
}
});
};
})
When I run the program on localhost, I am able to reach the
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
line with no issues. Anything after does not run.
You need check filterPets value, it must be true/false then model binder can map with bool type.
With primitive type (bool, int, float) you should use nullable type bool? for preventing case the value incorrect format.
[HttpPost]
public ActionResult MapFilter(string filterLake, bool? filterPets)
{
}
With this paramter if filterPets has wrong value, it will be null.
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();
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);
How to show message(to inform user if group is added successfully or not) using Javascript and JQuery instead of throwing an erro. Actually this code check if group name already exist in database.
Controller :
[HttpPost]
public int CreateGroup(UserGroup group)
{
return bc.Create(group, user.id);
}
User group class:
UserGroupDalc Dalc = new UserGroupDalc();
public int Create(UserGroup group, int creatorId)
{
if(ByName(group.name) != null) throw new ArgumentException(string.Format("Group name: {0} is already exist.", group.name));
return Dalc.CreateGroup(group, creatorId);
}
User group dalc class:
public int CreateGroup(UserGroup group, int creatorId) {
connection();
com = new SqlCommand("spp_adm_user_group_ins", conn);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#name", group.name);
com.Parameters.AddWithValue("#userid", group.creator_id);
conn.Open();
int i = com.ExecuteNonQuery();
if (i >= 1)
{
return 1;
}
else
{
return 0;
}
This js for posting data:
save: function () {
var jForm = $("#form1");
Metronic.blockUI();
GroupAPI.create(jForm.serialize(),
function (data) {
console.log(data);
},
function (error) {
console.log(error);
},
function () { Metronic.unblockUI(); });
}
}
}();
var GroupAPI = function () {
var url_create = "api/usergroup/createGroup";
var url_list = "api/usergroup/list";
return {
create: function (item, done, fail, always) {
var jqxhr = $.post(url_create, item);
jqXhrHandler(jqxhr, done, fail, always);
}
}
}();
Change user group class
UserGroupDalc Dalc = new UserGroupDalc();
public int Create(UserGroup group, int creatorId)
{
if(ByName(group.name) != null){
return 1;
}
return Dalc.CreateGroup(group, creatorId);
}
js
save: function () {
var jForm = $("#form1");
Metronic.blockUI();
GroupAPI.create(jForm.serialize(),
function (data) {
//console.log(data);
if (data == 0)
{
alert('added');
}else if(data == 1){
alert('already exist');
}
},
function (error) {
console.log(error);
},
function () { Metronic.unblockUI(); });
}
}
}();
it will be better to response a 422 status code, in this case indicate validation failed and server is not able to process the request, you can as well put the user readable message in the response response body
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
I have this code in my ActionResult
public ActionResult Copy( int bvVariableid ) {
var iReturn = _bvRepository.CopyBenefitVariable( bvVariableid, CurrentHealthPlanId, CurrentControlPlanId, _bvRepository.GetSecInfo( ).UserId, IsNascoUser());
if (iReturn == -999)
return new JavaScriptResult() { Script = "alert(Unique variable name could not be created');" };
if( iReturn != -1 )
return Json( new { RedirectUrl = string.Format( "/BvIndex/Index/{0}?bvIndex-mode=select", iReturn ) } );
return RedirectToRoute( "Error" );
}
This is the code i have in my View.
CopyBenefitVariable = function (bvId, bvName) {
if (confirm('Are you sure you want to copy from the Benefit Variable ' + bvName + ' ?')) {
$.post(
"/BvIndex/Copy/",
{ bvVariableid: bvId },
function (data) {
window.location = data.RedirectUrl;
}, "json");
}
};
When IReturn is -999 I am not getting the JavaScriptResult alert box on my page.
is that something I am doing wrong here?
Can any body help me out.
Thanks
I thing, there is a bug in this line:
return new JavaScriptResult() { Script = "alert(Unique variable name could not be created');" };
Corrected :
return new JavaScriptResult() { Script = "alert('Unique variable name could not be created');" };
Your problem is likely stemming from your client-side JavaScript. The .post() method in ajax is actually a shortcut for:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
So your client-side code is telling jQuery to interpret the result as a json object (even though you sent back a script).
$.post(
"/BvIndex/Copy/", // url
{ bvVariableid: bvId }, // data
function (data) {
window.location = data.RedirectUrl; // success
},
"json" // dataType
);
I would change your code to look like this:
public ActionResult Copy( int bvVariableid ) {
var iReturn = _bvRepository.CopyBenefitVariable( bvVariableid, CurrentHealthPlanId, CurrentControlPlanId, _bvRepository.GetSecInfo( ).UserId, IsNascoUser());
if (iReturn == -999)
return new Json(new { type = "msg", data = "Unique variable name could not be created" });
if( iReturn != -1 )
return Json( new { type = "url", data = string.Format( "/BvIndex/Index/{0}?bvIndex-mode=select", iReturn ) } );
return RedirectToRoute( "Error" );
}
And your view code should look like this:
CopyBenefitVariable = function (bvId, bvName) {
if (confirm('Are you sure you want to copy from the Benefit Variable ' + bvName + ' ?')) {
$.post(
"/BvIndex/Copy/",
{ bvVariableid: bvId },
function (data) {
if (data.type == "url") {
window.location = data.RedirectUrl;
} else if (data.type == "msg") {
alert(data.data);
}
}, "json");
}
};
You can mark down my answer if you like, but it is generally accepted that the JavaScriptResult was a bad move on the ASP.NET MVC team's part. That being said, your sample already returns a Json Action Result for one of your conditions. You could do the same for both items. If you altered your JSON object like:
return Json( new { success = bool, RedirectUrl = value } );
Then you could change your client function to something like:
function (data) {
if(data.success === true) {
window.location = data.RedirectUrl;
} else {
alert('Unique variable name could not be created');
}
}
I know it doesn't directly address the issue with JavaScriptResult, but it should get the intended result of the code.