populate drop down list with json - javascript

I am trying some stuff and populating drop down list with a json and javascript for some reason I am getting a console error when trying to populate
I am using Scripts/jquery-2.0.2.js
this is the error:
Failed to load resource: the server responded with a status of 404 (Not Found)
POST //localhost:9819/Home/Home/Test 404 (Not Found)
jquery-2.0.2.js:7858 send jquery-2.0.2.js:7858 jQuery.extend.ajax
jquery-2.0.2.js:7314 RetrieveData Index:45 (anonymous function)
Index:64 jQuery.event.dispatch jquery-2.0.2.js:4692 elemData.handle
This is the View Code:
<script>
$(document).ready(function () {
var Load = false;
function RetrieveData() {
if (Load == false) {
Load = true;
$.ajax({
url: <%= Url.Action("Test", "Home") %>
data: "{}",
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
$("#selectMe").html(data);
Load = false;
},
error: function (data, status, jqXHR) {
alert("Error: " + data);
Load = false;
}
});
}
}
$(document).on("click", "#test", function () {
RetrieveData();
});
});
</script>
<input type="submit" id="test" />
<select id="selectMe"></select>
Controller:
public string GenerateHTMLforDropDownList(Dictionary<string, string> myData)
{
string HTMLString = "";
foreach (KeyValuePair<string, string> k in myData)
{
HTMLString += "<option value=\"" + k.Key + "\">" + k.Value + "</option>";
}
return HTMLString;
}
[HttpPost]
public JsonResult Test()
{
Dictionary<string, string> myData = new Dictionary<string, string>();
myData.Add("0", "Mike");
myData.Add("1", "Mark");
myData.Add("2", "Karl");
myData.Add("3", "Rhona");
return Json(GenerateHTMLforDropDownList(myData), JsonRequestBehavior.AllowGet);
}
any help of how I can fix this thanks

As the error states, the resource is not found. Look at the URL in the error:
http://localhost:9819/Home/Home/Test
Assuming you're not doing anything more custom, if you have a Test action on a Home controller then the URL should be:
http://localhost:9819/Home/Test
Notice also how you're specifying the URL in your code:
url: "Home/Test"
If you're currently at http://localhost:9819/Home/Anything then that relative URL says to look for a resource called Test in a "subdirectory" (using the word loosely) of the current resource. So there's your problem.
Instead of specifying the URL manually like that, use the Url.Action method in MVC. Something like this:
url: '#Url.Action("Test", "Home")'
This will generate a fully-qualified URL from server-side code regardless of where your current context is, so you don't have to adjust it based on the current URL or anything like that.

I have not done this in MVC but I've done this countless times in Web Forms and it looks like your URL might be the problem...
//localhost:9819/Home/Home/Test
In your ajax call you should probably adjust this line...
url: "Home/Test"
and make it look something like ...
url: <%= Page.ResolveUrl("~/Home/Test.asmx") %>
Sorry if this is way off base for MVC.

You need to change your button type to 'button' not submit as this is ajax call

Related

AJAX indicates that WEBMETHOD was successful, but it never actually triggers the webmethod on code behind

I've been through countless posts and cant figure out what I am doing wrong. I have a asp.net website with C# code behind. In it, I need for a javascript function on the .aspx page to trigger a method on the aspx.cs page. I wrote the following code:
.aspx page (my ScriptManager):
</head>
<body id="bodycontainer">
<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePartialRendering="false" EnablePageMethods="true"/>
The Javascript function using ajax on the .aspx page:
function ValidateForm() {
$.ajax({
type: "POST",
url: "default.aspx/Save",
data: {},
contentType: "application/json; charset=utf=8",
// dataType: "json", // NOT NEEDED IF NO RETURN VALUE
async: true, // OPTIONAL
success: function (msg) {
alert("success");
},
error: function (msg) {
alert("failed");
}
});
}
The aspx.cs page (Code Behind page):
[WebMethod]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default();
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
public void btnSave_Click()
{
// METHODS CODE HERE
}
The ValidateForm function responds with "success", however, it doesn't seem like it is even triggering the WebMethod on the Code Behind page. If I use the I.E. Console Network tab, I can see the POST request. However, on the code behind method, it never triggers the breakpoints in debug (Not sure if it should according to some posts). At one point I inserted line to throw a DivideByZero exception and it never raised the exception.
So, to summarize, I get confirmation that he Javascript call to the WEBMETHOD worked by virtue of the success message and the POST message in the F12 Console Network tab. However, it doesn't seem that the WEBMETHOD ever fires. Any help would be appreciated !
You could try this to test an error instead of throwing an exception
Response.Clear();
Response.StatusCode = 500;
Response.End;
Not sure what I did, but I think adding "UseHttpGet = false" allowed it to finally execute the webmethod.
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default(); // SINCE THIS METHOD IS STATIC, WE HAVE TO INSTANTIATE AND INSTANCE OF THE DEFAULT PAGE CLASS TO ACCESS METHODS ON THIS PAGE
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
function ValidateForm() {
var text = "This is a Test";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf=8",
data: "{}",
url: "default.aspx/Save",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("status: " + textStatus);
alert("Error: " + XMLHttpRequest.responseText);
}
});
}

Value passed by ajax from Javascript to C#, Replied but not saved

I pass a value to my C# part with ajax and I get a response back. But I can't save the value or use it in my C# code. More information below:
Ajax Call: (gallery.aspx)
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&typeIds=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
Code Behind (CodeFile):(gallery.aspx.cs)
Update: Full C# code snippet
public partial class gallery : System.Web.UI.Page
{
public List<string> images = new List<string>();
public List<string> imagesList = new List<string>();
public List<string> filteredImagesList = new List<string>();
public List<string> testList = new List<string>();
protected string imagesName;
protected string filterType;
protected void Page_Load(object sender, EventArgs e)
{
if (Request["call"].ParseString() == "ajax")
{
Response.Write(Request["typeIds"].ParseString().TrimEnd(','), true, ResponseType.Json);
filterType = Request["typeIds"].ParseString().TrimEnd(',');
}
else
{
filterType = "Not Assigned!";
}
}
}
Output on the page: Not Assigned!
Meaning <h1><%=filterType%></h1> in aspx file returns the else statement from aspx.cs file
But I get the response back in my javascript while console.log("From AJAX: " + resp) shows the result.
BUT I can't use filtertype's value in my c# codefile.
I can't understand how come the Response.Write(Request["type"].ParseString().TrimEnd(','), true, ResponseType.Json); gives back the Request["type"] to js part but don't save it for my codefile. Should it be anything like Response.Read or Response.Save or something?
Does someone know what is going on in here?
You can store the ajax response in a hidden field and then access that hidden field value in server side code.
<asp:HiddenField ID="HiddenField1" runat="server" />
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&type=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
$('#<%=HiddenField1.CliendId%>').val(resp);
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
You can then access in server side code like this:
HiddenField1.Value
OK. It will never be assigned in the way how you did it. Simply because when the page is loading and all controls are rendering no ajax calls are taking into account Page Life Cycles. Because of that on page load filterType is not assigned.
Although you have a couple of options
Use Ajax with update panel and PageRequestManager class
Change the value through JQuery or Vanilla JS by using <%=filterType.ClientID%>
If you need only front-end representation you can use either option. If you need it for further back-end I'm afraid option 1 only choice for you.

show values entered in form as a table before getting submitted

First, I do not have much talent in ajax so please consider that while answering. Here I want to get all the values which I inserted into the form in a table before getting submitted but unfortunately am not getting the results I want. So far I have done this. Please have a look.
<script>
var form_data={ agent_name: $('#agent_name').val(),
type: $('input[name="type"]').val(),
number: $('#number').val(),
quantity: $('#quantity').val()
}
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>admin_control/ajax_data',
data: form_data,
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
alert(len);
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].agent_name && data[i].type){
txt += $('#table').append('<tr class="item-row"><td><input type="hidden" id="add_type" name="add_type[]" value="super">Super</td><td><input type="hidden" id="add_amount" name="add_amount[]" value="10">745</td><td><input type="hidden" class="add_quantity" id="add_quantity" name="add_quantity[]" value="10">10</td><td name="add_amount" id="add_amount">100</td><td><input type="checkbox" class="add_checkbox" name="layout" id="add_checkbox" value="1" checked></td></tr>');
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
</script>
Here I want to pass the values of form_data in to the table I had written and how can we pass that and did it compulsory to use the url in ajax while using this am getting an error like error: parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
Here is my controller
public function ajax_data()
{
$array = array("agent_name" => "admin","number"=>"785","type"=>"super","quantity"=>"10");
$data['json'] = $array;
echo json_encode($data);
}
The Ajax post will call the controller method for post values. The ajax code usually correct but you have not defined url.
url: '',
Firstly define a method (ex: HomeController) then set ajax url parameter like
url: '#Url.Action("Save","Home")' or url: 'Save/Home'
[HttpPost]
public JsonResult Save(string agent_name, string type , int number,int quantity)
{
// return json
}
Note :
The data types you send from the form with the method types must be
the same.
Well, just to give you some hints to work on: The Ajax call could look like this:
$.ajax({
type: 'POST',
url: 'echodata.php',
data: form_data,
dataType:"json",
success: function(data){
$('#table').append('<tr><td>'+data.agent_name+'</td>' // + more columns ...
+'</tr>');}
);
The php script should really be something that processes the incoming information (passed as the $_POST array) into some other data that will ultimately be echoed as JSON string.
This is just a trivial version of echodata.php for testing:
<?php
echo json_encode($_POST);
?>
EDIT:
While you have fixed your URL attribute and have added a "controller" on the server your Ajax success function still expects something it will not get. Your PHP script delivers a JSON string that will be parsed into as a JavaScript object and not an array. The object will not have the length property your success function tries to use. Instead you should be looking for the json property.
So, there is no point for the for loop, instead you can use data.json.agent_name, data.json.number and data.json.type (etc.) properties directly. Your current .append() also only adds a static string to your table. This should of course be changed to use the freshly received values.

Can't send array from jQuery to MVC 4 controller

I've googled this up and checked all over StackOverflow but I must be missing something... I have unobtrusive jQuery that hijaks a simple button click. It counts up the checkboxes and adds each checked boxes value to an array. The list is correct when I use an alert box in jQuery but the array never makes it to the controller side. The code flows to the controller but I break on var resolutionViewModel=new ResolutionViewModel(); and check trans - the argument is null. I'm new to jQuery and could really use the help here.
jQuery
// Return the selected transactions
function resolveTransactions() {
$('#btnResolve').click(function() {
var selectedTransactions = new Array();
$('input[name="chkTransaction"]:checked').each(function() {
selectedTransactions.push(this.value);
});
if (selectedTransactions.length > 0) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/AuditLog/Home/ResolutionFormDisplay',
contentType: 'application/json; charset=utf-8',
data: {trans : selectedTransactions},
traditional: true,
success: function (data) { alert(data); },
error: function(xhr, status, errorThrown) { alert("Error: " + errorThrown); }
});
}
});
};
Controller side
[HttpPost]
public PartialViewResult ResolutionFormDisplay(List<string> trans)
{
var resolutionViewModel = new ResolutionViewModel();
// fill Usernames dropdown selector in ViewModel
// fill Status dropdown selector in ViewModel
// fill list of transactionIds in ViewModel
return PartialView("_ResolutionDialog", resolutionViewModel);
}
Try having your controller accept a List, rather than just a single string (since you're not passing a single string):
[HttpPost]
public PartialViewResult ResolutionFormDisplay(List<string> value)
{
var resolutionViewModel = new ResolutionViewModel();
// fill Usernames dropdown selector in ViewModel
// fill Status dropdown selector in ViewModel
// fill list of transactionIds in ViewModel
return PartialView("_ResolutionDialog", resolutionViewModel);
}
Posted JSON needs to have named properties matching parameters in your controller method. Check the 'network' tab in Chrome dev tools and see exactly what you're posting, it's probably something like this:
"{\"value\":\"...\"}"
There is no value property to pass to your controller method's value parameter. I think the best would be just to get rid of the `JSON.stringify" and accept a list like Colin's answer, but if you want to take it as a string, the JSON string needs to be the value property of an object, not the other way around:
data: {value : JSON.stringify(selectedTransactions)},
Try passing your array as follows:
data:"{'trans':" + JSON.stringify(selectedTransactions)+"}"
Your method should be as follows:
public void Method(List<string> trans)
{
//Your implementation
}
SOLUTION:
The $.ajax postback was not sending properly formatted data to the controller. I discovered this by using the network tab in IE and looking at the Request Body of the POSTed http. It looked like this:transaction_table_length=10&chkTransaction=22&chkTransaction=23 -- It should have looked like this: {"trans":["22","23"]}. To solve this issue I stringified the property name and array as shown below, changed the dataType to 'text', and made the parameter on the controller action method take a String[] trans.
jQuery
// Return the selected transactions
function resolveTransactions() {
$('#btnResolve').click(function() {
var selectedTransactions = new Array();
$('input[name="chkTransaction"]:checked').each(function() {
selectedTransactions.push(this.value);
});
if (selectedTransactions.length > 0) {
$.ajax({
type: 'POST',
dataType: 'text',
url: 'http://localhost/AuditLog/Home/ResolutionFormDisplay',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ trans:selectedTransactions }),
traditional: true,
success: function (data) { alert(data); },
error: function(xhr, status, errorThrown) { alert(" Error: " + errorThrown); }
});
} else {
alert('You must select (check) at least one transaction to apply a resolution.');
return false;
}
return false;
});
};
MVC 4 controller action
[HttpPost]
public PartialViewResult ResolutionFormDisplay(string[] trans)
{
var resolutionViewModel = new ResolutionViewModel();
// fill Usernames dropdown selector in ViewModel
// fill Status dropdown selector in ViewModel
// fill list of transactionIds in ViewModel
return PartialView("_ResolutionDialog", resolutionViewModel);
}

getJSON is not calling the controller action

I don't know why this is happening since there are other functions in this page that use also getJSON and they do work. I have the following JavaScript Code
function openSOPNotesDialog() {
var url = '<%: Url.Action("GetSOPNote", "SalesOrder") %>';
var id = <%: Model.SodID %>;
$.getJSON(url, { sodId : id }, function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
});
}
and then I have this method on the SalesOrderController class
public JsonResult GetSOPNote(int sodId)
{
var service = new SodSrv();
var note = service.GetSOPNotes(sodId);
return Json(note, JsonRequestBehavior.AllowGet);
}
However, the method is never called in the debugger and data is returned as null (which is what I'd expect). As I said before there are other calls in this page and they are also doing GET requests so I don't know what may be the cause.
Sounds like the browser is pulling the data from the cache since it is a get request. Make sure to set no cache headers on the server if it is not meant to be cached.
Try adding an error handler to try to track down what the issue is:
$.ajax({
dataType: 'json',
url: url,
data: { sodId : id },
success: function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("oops: " + textStatus + ": " + jqXHR.responseText);
}
});
I suspect that the reason is that getJSON uses get method and controllers normally allowed to accept only post methods. It's ease to check using any browser firebug for example.

Categories

Resources