I have an ASP.NET application where I am invoking a controller methode from JavaScript. My JavaScript code looks like this:
function OnNodeClick(s, e) {
$.ajax({
type: "POST",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (data) {
if (data != null) {
$('#GridView').html(data);
}
},
error: function (e) {
alert(e.responseText);
}
});
}
This calls the Home controller's DeviceManifests() method.
This is what the method looks like:
public ActionResult DeviceManifests(Guid selectedRepo)
{
var repoItem = mock.GetRepoItem(selectedRepo);
return View("Delete", repoItem.childs);
}
The method gets invoked but the problem is the Delete-View doesn't get rendered. There's no error, just nothing happens.
How can I update my code to get my desired behaviour?
Do like below code so if you have error you will have it in alert box or success result will rendered in DOM
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
dataType: "html",
success: function (data) {
if (data != null) {
$('#someElement').html(data);
}
}
},
error: function (e) {
alert(e.responseText);
}
});
You can do the redirect in the javascript side.
function OnNodeClick(s, e) {
$.ajax({
type: "GET ",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (msg)
{
window.location = msg.newLoc;
}
});
}
Make sure you include the redirect url in action and return JsonResult and not ActionResult. I'd also include pass the guid so that the destination Action and let it look up the data.
Related
I have this code on my JavaScript file:
temp="string";
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: myJson,
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(temp.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
console.log(errorThrown);
ConnectionChanged();
}
});
And this controller:
[HttpPost]
public string updateStatus(string updatedJson)
{
var Player = JsonConvert.DeserializeObject<GameDataClass>(updatedJson);
var Opponent = JsonConvert.DeserializeObject<GameDataClass>(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.WebRootPath, Player.OpponentID + ".json")));
... }
I tried to change $.ajax to $.post method, also changed
public string updateStatus
to
public JsonResult updatedStatus
But neither of this didn't work. myJson on javascript contain data but when it reaches controller updatedJson is empty. I've never had this kind of experience so I'm using this code from another project and it works very well there. So can somebody suggest me what I'm doing wrong?
temp="string";
// (0)
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus?updatedJson=' + temp, // (1)
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '', // (2)
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(response.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
ConnectionChanged();
}
});
Or if this does not have to be passed as a parameter, then do the following:
(0) var formData = new FormData(); formData.append('updatedJson', temp);
(1) url: '/MemoryGame/updateStatus',
(2) data: formData,
$.ajax is a fonction from the jQuery library, does your project include it ?
You can also check the Javascript console of your browser to see if it contains errors. On Firefox and Chrome you can access it by pressing F12.
I would like to call my WEB API in .NET Core from the jQuery like below:
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
JsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
return Json(welCome, JsonSettings);
}
catch(Exception ex)
{
throw ex;
}
}
And the jQuery caller:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "http://localhost:5000/api/mycontroller/GetText?callback=?",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
if (data.success) {
alert('Success -> ' + JSON.stringify(data.statusText));
}
},
error: function (data) {
alert('Error -> ' + JSON.stringify(data.statusText));
}
});
});
</script>
The API is calling successfully but it seems it will then redirect to error function in my Ajax and show the error alert with a "success" as it's statusText. I mean this: Error -> "Success" I am not sure why this happens?
I would like to print welCome as a success result and in the alert command.
Also please note that I am calling this API from another project, I mean the jQuery's AJAX code is inside another project. I am not sure if it is important or not at all.
The jQuery's AJAX Caller path: file:///C:/Users/Me/Desktop/Path/index.html
The API's address: C:\Users\Me\Documents\Visual Studio 2017\Projects\ThisProject\MyAPI
And the URL of this API: url: "http://localhost:5000/api/mycontroller/GetText",
Try the C# Code in the following manner :
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
return Ok(new { message = welCome });
}
catch(Exception ex)
{
throw ex;
}
}
Try the Jquery Code in the following manner :
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'GET',
url: 'http://localhost:5000/api/mycontroller/GetText',
success: function (response) {
alert('Success' + response.message);
},
failure: function (response) {
}
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
Just wondering if this is even possible.
I am making a store web application in asp.net MVC 4 i guess.
And my articles have a category and a sub category.
So I got this code which I can't make to work.
Script:
$("#ManageCategories").click(function (e) {
$.ajax({
type: "GET",
url: "Acp/LoadManageCategories",
success: function (response) {
$("#main-acp-display").html(response);
},
error: function () {
alert("Error!");
}
});
});
$(".get-subcategories").click(function () {
$.ajax({
type: "GET",
url: "Acp/LoadManageSubCategories",
data: { subCategoryId: $(this).attr("id") },
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$("#subcategory-display").html(response);
},
error: function (response) {
alert(response.responseText);
}
});
});
(the first part works like a charm)
Controler:
[CustomAuthorize(Roles.Admin)]
public ActionResult LoadManageCategories()
{
IEnumerable<CategoryModel> model = _categoryManager.GetAll().Select(x => (CategoryModel)x);
return PartialView("Partial/_LoadManageCategories", model);
}
[CustomAuthorize(Roles.Admin)]
public ActionResult LoadManageSubCategories(string subCategoryId)
{
int id = Convert.ToInt32(subCategoryId);
IEnumerable<SubCategoryModel> model = _categoryManager.GetAllSubCategoriesByCategoryId(id).Select(x => (SubCategoryModel)x);
return PartialView("Partial/_LoadManageSubCategories", model);
}
Now you see the first level code works. When I click a div on index it loads all categories. But the other function wont load unless I place the clickable div on index page too and I wanted it to be a part of first partial view.
So it should be Button(click) > Shows all categories(click any) > Loads subcategories.
Is this even possible?
Offtopic: Does MVC work only on one level? Cause I remember trying to have a Model with List of other models inside of it and inside this list there was another model and it wasn't so good xD (Managed to find simpler solution, but this is where I got the mvc one level only thought)
Update:
So #bigless had an idea to make this a function so here it is so far:
function createSubcategories(id) {
$.ajax({
type: "GET",
url: "Acp/LoadManageSubCategories",
data: { subCategoryId: id },
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$("#subcategory-display").html(response);
},
error: function (response) {
alert(response.responseText);
}
});
};
And calling it by:
<button onclick="createSubcategories(1)"><i class="fas fa-angle-double-right main-cat-icon"></i></button>
Current error:
Uncaught ReferenceError: createSubcategories is not defined
at HTMLButtonElement.onclick (Acp:89)
You can not attach event listener to DOM element(.get-subcategories) that does not exist yet. Try something like $(document).on('click', '.get-subcategories', function() { .. or:
$("#ManageCategories").click(function (e) {
$.ajax({
type: "GET",
url: "Acp/LoadManageCategories",
success: function (response) {
$("#main-acp-display").html(response).ready(function() {
$(".get-subcategories").click(createSubcategories);
});
},
error: function () {
alert("Error!");
}
});
});
function createSubcategories() {
$.ajax({
type: "GET",
url: "Acp/LoadManageSubCategories",
data: { subCategoryId: $(this).attr("id") },
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$("#subcategory-display").html(response);
},
error: function (response) {
alert(response.responseText);
}
});
};
I have a javascript function with a ajax call. It reaches safely to the controller with no problem. But when the controller give back the result into json format, then I have not get the data in view page.
Below the code snippets:
Controller Action Method:
public JsonResult GetContactDetails(string contactId)
{
Contact objContact = _contactService.Get(contactId.TryToInt());
return Json( objContact, JsonRequestBehavior.AllowGet);
}
Javascript Method:
function GetContactDetails(contactId, designation, mobile) {
$.ajax({
cache: false,
url: '#Url.Action("GetContactDetails", "Clients")',
type: "GET",
async: false,
data: {contactId:contactId},
dataType: 'json',
success: function (result) {
alert("Yes");
debugger;
},
error: function () {
alert("error");
}
});
}
I'm not sure why my ajax success isn't being triggered/called.
My controller is called and the code is executed fine. I'm not returning anything, so my method is a void! Do I need to return something (ActionResult/JSonResult/etc) to get the success to trigger?
Here is my controller code.
public void DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
}
Here is my ajax call.
$.ajax({
url: '/ManageSpaces/DeleteEvent',
dataType: 'json',
data: {
eventId: eventId,
},
success: function() {
//var obj = JSON.parse(doc);
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}
});
Yes, you need to return JsonResult:
[HttpPost]
public JsonResult DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
return Json("{status:"OK"}");
}
Since you are changing back-end data, set it to POST:
$.ajax({
url: '/ManageSpaces/DeleteEvent',
method: 'POST',
dataType: 'json',
data: {
eventId: eventId,
},
success: function(response) {
if(response.status=="OK"){
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}else{
console.log("Error occured")
}
}
});