Controller action is not called in view using Javascript - javascript

I am very much new in MVC. I have javascript function that reads xml string and displays various values. One of the element in XML is in encrypted form. I have written method in controller that will return decrypted string but I am not able to call that method inside my javascript method using ajax. Below the code of controller method and javascript code.
[HttpPost]
public ActionResult DecryptMessage(string message)
{
string decryptedMessage= Encryption.DecryptData(message);
return Json(decryptedMessage);
}
part of Javascript code
if ((x[i].nodeName).toUpperCase() == "MESSAGE" ) {
//alert(childnd.nodeValue);
$.ajax({
type: "POST",
data: { value: childnd.nodeValue },
url: "/QueryController/DecryptMessage",
dataType:"string",
Success: function (result) {
if (result > 0) {
stringDetails = stringDetails + '<br><strong>Value:</strong>' + result + '<br>';
}
})
}
I am not able to figure out what is wrong.

Since this is your URL that you work on: localhost/LogViewerPortal/Query/Index, your AJAX should fire to the same URL. Also, change Success to success:
if ((x[i].nodeName).toUpperCase() == "MESSAGE" ) {
//alert(childnd.nodeValue);
$.ajax({
type: "POST",
data: { message : childnd.nodeValue },
url: "/LogViewerPortal/Query/DecryptMessage",
success: function (result) {
if (result) {
stringDetails = stringDetails + '<br><strong>Value:</strong>' + result + '<br>';
}
})
}
And if you want to return a string from your controller, you could change to:
[HttpPost]
public ActionResult DecryptMessage(string message)
{
string decryptedMessage= Encryption.DecryptData(message);
return Content(decryptedMessage);
}

Related

How to pass a list from spring controller to ajax in jquery

This is my Jquery! Here i am not getting success response, instead a error response is thrown when a list is returned from controller to below jquery. Please let me know where i am going wrong.
//ajax method to retrieve the data from controller where controller returns list
function doAjaxPost() {
// get the form values
var pid = $('#pid').val();
$.ajax({
type: "GET",
url: "http://localhost:8085/HMS/iochart1.html",
data: "pid=" + pid,
success: function (response) {
alert(response.list4);
$.each(response, function (index, datec) {
alert(datec.name); //to print name of employee
});
},
// Even though controller returns the list,but i am not getting the above success response,instead below error method is executed.
error: function (e) {
alert('Error: ' + e);
}
});
}
Below is the controller which returns the list.
#RequestMapping(value="/iochart1", method = RequestMethod.GET)
public #ResponseBody List<Iochart> iochart1(#ModelAttribute("s") Iochart s) {
System.out.println("Patient"+s.getPid());
List<Iochart> list4 = dao.getPatientdet1(s.getPid());
return list4;
}
getPatientdet1() which retrieves the data from database
public List<Iochart> getPatientdet1(String pid) {
// TODO Auto-generated method stub
System.out.println(pid);
return template.query(
"select pid,name,fileno,age,gender,date,wardno,doctord,doctsig,ratef,nursesig,time,type,amount,typecommence,amtgiv,urine,vomitus,remarks from iochart where pid='"+pid+"'",
new RowMapper<Iochart>() {
public Iochart mapRow(ResultSet rs, int row) throws SQLException {
Iochart i = new Iochart();
i.setPid(rs.getString(1));
i.setName(rs.getString(2));
i.setFileno(rs.getString(3));
i.setAge(rs.getString(4));
i.setGender(rs.getString(5));
i.setAdmdate(rs.getString(6));
i.setWardno(rs.getString(7));
i.setDoctord(rs.getString(8));
i.setDoctsig(rs.getString(9));
i.setRatef(rs.getString(10));
i.setNursesig(rs.getString(11));
i.setTime(rs.getString(12));
i.setOraltype(rs.getString(13));
i.setOralamt(rs.getString(14));
i.setOralcommence(rs.getString(15));
i.setAmtgiv(rs.getString(16));
i.setUrine(rs.getString(17));
i.setVomitus(rs.getString(18));
i.setRemarks(rs.getString(19));
System.out.println(rs.getString(2));
return i;
}
}
);
}
Change your controller method like so. Mind the #RequestParam that is used to get the pid
#RequestMapping(value="/iochart1", method = RequestMethod.GET)
public #ResponseBody List<Iochart> iochart1(#RequestParam(name = "pid") String pid) {
return dao.getPatientdet1(pid);
}
And your ajax url like so
function doAjaxPost() {
// get the form values
var pid = $('#pid').val();
$.ajax({
type: "GET",
url: "http://localhost:8085/HMS/iochart1", //Don't postfix .hmtl
data: "pid=" + pid,
...
});
}

Ajax POST and Stringify Confusion

I am learning about POST with Ajax and I've noticed a lot of examples using stringify on static arrays.
In my example I am building array via jQuery objects extracted from <input> values.
Jquery
function PostEdit(vData){
var content = JSON.stringify(vData); //content = "[{"Id":"1","Date":"7/12/2017 12:00:00 AM"}]"
$.ajax({
url: '#Url.Action("Index", "PostViewData")',
type: "POST",
data: JSON.stringify({ ViewData : vData }),
contentType: "application/json",
success: function (result) {
alert("success" + result);
},
error: function (result) {
alert("failure" + result);
}
});
return;
}
Controller
[HttpPost]
public ActionResult Index(List<DataViewModel> ViewData )
{
if(ViewData != null)
{
var json = new { success = true };
return Json(json);
}
return Json(false);
}
ViewModel
public class DataViewModel
{
public DataViewModel(string id, string date)
{
Id = id;
Date = date;
}
public string Id { get; set; }
public string Date { get; set; }
}
Where DataViewModel is a class that consists of two values, Id, and Date which correspond to my JS object.
Since vData enters the function as value vData = [Object], When I call .stringify(vData) it returns content = "[{"Id":"1","Date":"7/12/2017 12:00:00 AM"}]"
The value of content above is how I see most examples structured before stringify such as the example here.
Once in this format, this is when most responses, examples call stringify anyway.
Now when I call .stringify(ViewData : vData) I dont even make it to the controller. Ajax fails to post. On the contrary when I call .stringify(ViewData : content), I make it to the controller, but with a null value. What am I missing / misunderstanding?
I'm looking for a better explanation of Ajax Post and Stringify, and how it interacts with the controller parameter.
Just add parameterless constructor to your model. With that change, your code will work as it is. ASP is unable to parse your json as DataViewModel since it's trying to call default constructor that doesn't exists.
public class DataViewModel
{
public DataViewModel()
{
}
//...other methods and members here
}
Please try the solution below.
There's another way of doing this
function PostEdit(vId, vDate){
$.ajax({
url: '/PostViewData/Index' // it should be '/controller/method'
type: "POST",
data: JSON.stringify({ Id: vId, Date: vDate}),
contentType: "application/json",
success: function (result) {
alert("success" + result);
},
error: function (result) {
alert("failure" + result);
}
});
return;
}
[HttpPost]
public ActionResult Index(string Id, string Date )
{
if(Id != null)
{
var json = new { success = true };
return Json(json);
}
return Json(false);
}
Update: In the controller method, it should be string id, string date
Update: The constructor should be parameterless. From the answer mentioned below
public DataViewModel()
{
}

How to make a AJAX GET call in ASP.NET MVC application

I am learning web development. And I just want to make a simple AJAX GET call in ASP.Net MVC Application and I want visualize how it works. But I am not able to do so. I am a beginner and I could have done any silly mistakes. But as of now there are no errors in my code.
Below is what I have:
So, I have a Index.cshtml file which is already loaded. Now in that page I want to make an Ajax GET call to one of the function that I have written in the HomeController and action name is Test. I just want to hit the breakpoint in that Test Action of Homecontroller and return something back to the Success of AJAX Call.
In HomeController I have below Action
[HttpGet]
public ActionResult Test()
{
return View("hello");
}
jQuery
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
}
Confusion: Do I need to create a cshtml for Test. But I actually do not want that. I just want the Test Action to return me one data. And I will display that data in my Already opened Index.csthml file.
Error: No error but I am not able to hit the breakpoint in Test Action of controller. Kindly note that Success of AJAX is hitting but I do not see any data. But I am sure it did not hit the test Action breakpoint.
Change your action method like this
[HttpGet]
public JsonResult Test()
{
return Json("myContent",JsonRequestBehavior.AllowGet);
}
And in your success method in 'html' variable you will get back "myContent".
Example :
function RemoveItem(ItemId) {
if (ItemId && ItemId > 0) {
$.ajax({
cache: false,
url: '#Url.Action("RemoveItem", "Items")',
type: 'POST',
data: { id: ItemId },
success: function (result) {
if (result.success == true) {
$("#CartItemGridDiv").load('#Url.Content("~/User/Items/CartItemGrid")');
alert('Item Removed successfully.');
}
else {
alert('Item not removed.');
}
},
error: function (result) {
alert('Item not removed.');
}
});
}
}
public ActionResult RemoveItem(int id)
{
if (id > 0)
{
bool addToChart = false;
addToChart = Utilities.UtilityClass.RemoveItem(id);
if (addToChart)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
public ActionResult CartItemGrid()
{
List<CartItems> oItemList = (List<CartItems>)Session[MvcMAB.StringConst.CartItemSession];
return View(oItemList);
}
Since you don't want to return a view, you might need to return Json() instead of View()
You need to Allow Get in the action. Like that:
public ActionResult SomeGetAction(int? id)
{
//Some DB query here
var myJsonList = myListQuery;
return Json(myJsonList, JsonRequestBehavior.AllowGet);
}
Or in case of just Simple string response:
public ActionResult SomeGetAction()
{
return Json("My String", JsonRequestBehavior.AllowGet);
}
I would recommend renaming html into response.
Also change that to this in Error Response section.
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (response) {
alert(response);
},
error: function (error) {
$(this).remove();
DisplayError(error.statusText);
}
});
Enjoy.
C#:
public JsonResult Test()
{
return Json("hello");
}
Jquery:
$.ajax({
url: '/Home/Test',
type: 'Post',
dataType: 'json',
success: function (html) {
alert(html);
},
error: function (error) {
alert(error);
}
});

Getting failed on returning string from API to JSON AJAX POST in mvc Javascript

$("#modelchange").change(function() {
$.ajax({
type: 'POST',
url: '#Url.Action("GetStore")',
dataType: 'json',
data: {
Id: $("#modelchange").val()
},
success: function(storeName) {
$('#storeName').text("Store : " + storeName);
},
error: function(ex) {
alert('Failed to load store Value');
}
});
return false;
});
API
[HttpPost]
public string GetStore(int Id)
{
string storeName = db.AddInktoStores.Single(a => a.InkId == Id)).Store.StoreName;
return storeName;
}
Above mentioned is a controller and JSON in my javascript.
I am trying to get Store Name but I keep getting throw into my error: function
Please Help!
Try to return data as:
[HttpPost]
public JsonResult GetStore(int Id)
{
string storeName = db.AddInktoStores.Single(a => a.InkId == Id)).Store.StoreName;
return Json(storeName);
}

Posting JSON string to ASP.NET MVC 3 action results in null parameter

I am posting a JSON string to asp.net MVC as follows.
AJAX call
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: JSON.stringify(currSelection),
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
In the controller:
[HttpPost]
[ActionName("OpcInsertCustomerProfile")]
public JsonResult OpcInsertCustomerProfile(string currSelectionData)
{
try
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var res = ser.Serialize(currSelectionData);
return Json(currSelectionData, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
return Json(new { error = 1, message = exc.Message });
}
}
Debugger indicates the action gets called successfully, however the incoming string parameter being received is always null. Firebug 'post' shows outgoing parameter is proper json object. I am expecting to see the JSON string as incoming parameter. Please note that I don't want to de-serialise it into proper object. All I want to do is store the string in JSON format 'as-it-is' in a database. Later on it needs be retrieved ans passed to Javascript as it is.
Try this :
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: { "currSelectionData" : "'" + JSON.stringify(currSelection) + "'" },
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
One way is to allow the action to receive the parameter as POST data instead of JSON "Stringified" data. To do that, post the data without JSON.Stringify. Hopefully this is what you need.
If not you might want to try creating an object just to receive this simple data.
Look at your action method: is it correct that method accepts string with serialized JSON, than serialized that string as JSON again and then dismiss the result and serializes and returns the same string again?
If you send request with application/json type ASP.NET MVC tries to deserialize received string and bind it to action parameters: in your case it tries to find property currSelectionData inside your JSON object. Is that property exists? Maybe you expect whole string is received as currSelectionData parameter? Then you need to use FormCollection or Request.Form instead because default model binder does not support this.
Actually i fill my state dropdown in selection of country with json i do like this
in my controller i have action it's return my data in json format like this it's below
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
in my view
<script type="text/javascript">
function cascadingdropdown() {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
i think this will help you...
When sending json through Ajax, I think this is the right approach for the data property in Ajax:
data: "{'parameterNameInAction':'" + JSON.stringify(jsonData) + "'}"

Categories

Resources