i pass json value my controller is working i checked my controller using break points but my json is not working it didn't responding alert message also not working please some one helpme friends. . .
My jquery
$('#Group').change(function () {
var name = $('#Tournament').val();
$.post("/DataCollection/Fee", { name: name, group: $('#Group').val() }, function (result) {
alert('hai');
$('#Fee').val(result.value.Fees);
$('#Count').val(result.value.NoOfboys);
$('#CName').empty();
$('#CName').append($("<option></option>").html("--SELECT--"));
$.each(result.Cname, function (key, value) {
$('#CName').append($("<option></option>").html(value).val(value));
});
}, "json");
});
My Controller
public JsonResult Fee(string name, string Group)
{
var value = entity.TblClsGroups.FirstOrDefault(x => x.TName == name && x.GroupName == Group && x.RecordStatus == 1);
var Cname = entity.TblGroups.Where(x=>x.RecordStatus==1 && x.TName == name && x.GroupName == Group).Select(c=>c.Cid);
var getFee = new { Cname, value };
return Json(getFee, JsonRequestBehavior.AllowGet);
}
try this:
return Json(new { Cname = Cname, value = value }, JsonRequestBehavior.AllowGet);
and in view use them like result.Cname and result.value
Try this:
var getFee = new { Cname = Cname, value = value };
Related
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);
I am working on MVC4 application in that this is Actionresult returns json result but i want to pass variable objservice.callid on view but i am returning json can it is possible to get value on view with the help of json result or having any method to pass the value of variable to view but return type shoould be json result.
Here is code in controller:
[HttpPost]
public ActionResult create(ServiceCall objservice)
{
AllViewBags();
string result = PartnerMaster.CreateServiceCall(objservice);
if (result == "")
{
ViewBag.id = objservice.callID;
return Json("Service Call = " + objservice.callID + " is Created successfully!");
} else {
return Json("This record is not added because of this error:=>" + result);
}
}
Here is code in view:
if (str.indexOf("successfully") != -1)
{
window.location.href = '#Url.Action("edit", "service_call", new { id = "CC" })'.replace("CC", '#ViewBag.id');
} else {
if (str.search("added") != -1)
{
window.location.href = '#Url.Action("service_call", "service_call")';
} else {
window.location.href = '#Url.Action("edit", "service_call", new { id = "CC" })'.replace("CC", callID);
}
}
I have try that objservice.callid variable store in viewbag and access on view it is not work.because view is not return controller.
can it is possible to store that variable in session variable then access on view.
Please give some suggestion ....
return as a json object with multiple values
[HttpPost]
public ActionResult create(ServiceCall objservice)
{
AllViewBags();
string result = PartnerMaster.CreateServiceCall(objservice);
if (result == "")
{
return Json(new { message = "Service Call = " + objservice.callID + " is Created successfully!", id = objservice.callID);
}
else
{
return Json(new {message = "This record is not added because of this error:=>" + result, id = 0});
}
}
and use this in the post success to redirect ...
I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.
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.
I have the folliwng script which actually make two calls to two seperate action methods, and update the related fields:-
<script type="text/javascript">
$(document).ready(function () {
$("#Switch_RackID").change(function () {
var idRack = $(this).val();
$.getJSON("/Switch/LoadDataCenterByRack", { id: idRack },
function (RackData) {
var select = $("#Switch_TMSRack_DataCenter_Name");
select.empty();
$("#Switch_TMSRack_DataCenter_Name").val(RackData.Text);
});
$.getJSON("/Switch/LoadZoneByRack", { id: idRack },
function (RackData2) {
var select = $("#Switch_TMSRack_Zone_Name");
select.empty();
$("#Switch_TMSRack_Zone_Name").val(RackData2.Text);
});
});
});
</script>
But my question is weather I can make a single call using getjson instead of doing two calls, and then update the related fields ? my action methods look as follow:-
public JsonResult LoadDataCenterByRack(int id)
{
string datacentername = repository.FindRack(id).DataCenter.Name;
var DCData = new { Text = datacentername, Value = datacentername };
return Json(DCData, JsonRequestBehavior.AllowGet);
}
public JsonResult LoadZoneByRack(int id)
{
string zonername = repository.FindRack(id).Zone.Name;
var ZData = new { Text = zonername, Value = zonername };
return Json(ZData, JsonRequestBehavior.AllowGet);
}
Can anyone advice please?
Thanks
Sure you can. You can return Anonymous object
Change your controller action as
public JsonResult LoadDataCenterByRack(int id)
{
string datacentername = repository.FindRack(id).DataCenter.Name;
var DCData = new { Text = datacentername, Value = datacentername };
string zonername = repository.FindRack(id).Zone.Name;
var ZData = new { Text = zonername, Value = zonername };
return Json(new {
DCData,
ZData
}, JsonRequestBehavior.AllowGet);
}
JavaScript
$.getJSON("/Switch/LoadDataCenterByRack", { id: idRack },
function (response) {
$("#Switch_TMSRack_DataCenter_Name").val(response.DCData.Text);
$("#Switch_TMSRack_Zone_Name").val(response.ZData.Text);
});
You can check what response you are getting by using console.log in JavaScript like
console.log(response)