I'm currently writing a MVC C# application. Everything works just fine. I have a bit of functionality, where I fill up a Bootstrap modal box using an Ajax call, but the new page gets cached, despite my efforts to prevent that.
On my main page I have the following actionhandler to fill up the modal box:
function setExtraPermsOrAtts(appID){
$.ajax({
cache:false,
url: "/Group/_modifyAppPermissionsOfGroup?appID=" + appID
}).done(function (result) {
$("#addApplicationBody").html(result);
$('#modal-add-application').modal('show');
});
}
This gets caught by the following method:
public ActionResult _modifyAppPermissionsOfGroup(int? appID = 0)
{
if (appID != 0)
{
ViewBag.selectedAppID = appID;
Session["selectedGroupAppID"] = appID;
ViewBag.modifyPermsLater = true;
}
Group group = (Group)Session["currentGroup"];
return View(group);
}
Another thing that might be relevant is the point where it 'goes wrong'. The resulting View in the Modalbox, has a few radio buttons, depending on the content of the database. There I do a razor statement to get the DB value:
bool valueOfRadButtons = BusinessLogic.Domain.GroupIS.getExistingGroupPermission(
Model.LoginGroupID, myItem.ApplicationPermissionID).LoginPermissionState;
Does anyone know where I'm going wrong? Is it the Ajax call? The ActionResult method in the Controller? Or the inline razor statement? I know the data gets saved properly, cause I see so in the DB
You can specify that the response shouldn't be cached like this:
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
It can be more easy if you make your own attribute and decorate the action with it as shown here.
Related
I have an array of file names:
[HttpPost]
public JsonResult GetJSONFilesList()
{
string[] filesArray = Directory.GetFiles("/UploadedFiles/");
for (int i = 0; i < filesArray.Length; i++)
{
filesArray[i] = Path.GetFileName(filesArray[i]);
}
return Json(filesArray);
}
I need this in AngularJS as a list of objects so I can ng-repeat it out and apply filters. I'm unable to figure out how to get the JSON from the MVC controller to AngularJS.
I've tried the following to make it visible to the view for angular to grab, but I don't know how to make the ng-init see the function to return the list. It erros on "SerializeObject(GetJSONFilesList())" saying it doesn't exist in current context.
<div ng-controller="MyController" data-ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(GetJSONFilesList()),
#Newtonsoft.Json.JsonConvert.SerializeObject(Model.Done))" ng-cloak>
</div>
EDIT:
I've tried using http.get.
Test one:
alert('page load');
$scope.hello = 'hello';
$http.get('http://rest-service.guides.spring.io/greeting').
then(function (response) {
$scope.greeting = response.data;
alert($scope.greeting);
});
alert($scope.hello);
The alert in the http.get never fires, the other alerts do however.
Test two:
$http({
url: '/Home/testHello',
method: 'GET'
}).success(function (data, status, headers, config) {
$scope.hello = data;
alert('hi');
});
[HttpPost]
public string testHello()
{
return "hello world";
}
This causes the angular to break and nothing in the .js works.
Test three
alert('page load');
$scope.hello = 'hello';
$scope.GetJSONFilesList = function () {
$http.get('/Home/testHello')
.success(function (result) {
$scope.availableFiles = result;
alert('success');
})
.error(function (data) {
console.log(data);
alert('error');
});
alert('hi');
};
alert($scope.hello);
[HttpPost]
public string testHello()
{
return "hello world";
}
Alerts nothing from within it, other alerts work.
Fixed:
After some googling, I've found that using .success and .error are deprecated and that .then should be used. So by using .then this resulted in the C# being hit via debug.
Then after using console.log on the returned value found that to have anything be returned I needed to return the value from C# using "return Json(myValue, JsonRequestBehavior.AllowGet); "
And by viewing the object in the console in Chrome by using console.log, I could see my values were in the data part of the returned object.
It was stored in data as an array (as I was passing an array).
I could then get the data out of there by assigning the returned value.data to a scope and could call that in the view {{result[1]}} etc.
return Json(filesArray, JsonRequestBehavior.AllowGet);
$scope.fileList;
$http.get("/Home/GetFileList").then(function (result) {
console.log(result)
$scope.fileList = result.data;
})
Imagine that you divide your front end in three layers (MVC or MVVM) whatever you want.
When you need info from server, the best practice is to separate the logic that makes the request and the logic that manipulates the data.
More info about how to make the request you can find it reading about REST APIS in Consuming a RESTful Web Service with AngularJS.
Normally one of the layers requires the use of services and you can have your controllers and your services (the place where you get the raw data from the server and you make the request. For that you need to use the $http service from angularjs.
$http: The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
So basically it shows you how to make get, post and put requests. One example from the documentation is :
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Pay attention to the url because there is the place where you let your request knwow which method is going to be hit on the server to take the action. If your request is succesful, then you can use the parameter called response. From there, you can do whatever you want. If you decide to make that request part from your controller, you can assign it directly to a variable on your scope. Pay attention if you need to serialize the data. Something like
$scope.myResponseName = response.name ;
The first documentation link from above shows this example which does exactly what I tell you.
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http.get('http://rest-service.guides.spring.io/greeting').
then(function(response) {
$scope.greeting = response.data;
});
});
After all the mentioned above, pay attention to what you want to display. Are you going to display the elements of an object array? The use on your HTML the ng-repeat directive. Are you going to display just a variable (No array nor object) then you use need to use an angular expression {{ }}
In summary:
By making an HTTP request, hit the correct method on server.
Make sure you are sending the JSON correctly and that the data is correct.
Retrieve the data on your response.
Assign the data to a variable on your scope and serialize the data if needed.
Display the data correctly depending if it is within an array, if it´s an object or if its just a variable.
I hope the explanation makes sense and check the documentation if you need more info.
You can build your viewmodel so that it contains the data you'd like to serialize and then pass it to angularJS in your view as follows:
<div ng-controller="MyController" data-ng-init="init(#JsonConvert.SerializeObject(myArrayData),
#Newtonsoft.Json.JsonConvert.SerializeObject(Model.Done))" ng-cloak>
and then in your angular controller have a function to receive the data as follows:
$scope.init = function (myArrayData) {
//do something with data
};
The above assumes you're trying to pass data from mvc to angularjs on page load. If you're trying to hit a controller and get data back to angularjs upon some event such as a button click, then you can write an angularjs function similar to the following (this will be an asynchronous request):
app.controller('MyController', function ($scope, $http, $window) {
$scope.ButtonClick = function () {
var post = $http({
method: "POST",
url: "/SomeController/SomeAjaxMethod",
dataType: 'json',
data: { path: $scope.Path},
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
//do something with your data
});
post.error(function (data, status) {
$window.alert(data.Message);
});
}
}
and your controller action would look something like:
[HttpPost]
public JsonResult SomeAjaxMethod(string path)
{
string[] filesArray = Directory.GetFiles(path);
for (int i = 0; i < filesArray.Length; i++)
{
filesArray[i] = Path.GetFileName(filesArray[i]);
}
return Json(filesArray);
}
other answers say to use .success in the angular function, .success and .error are deprecated, instead .then should be used.
Working result:
MVC:
public JsonResult GetFileList()
{
//form array here
return Json(myArray, JsonRequestBehavior.AllowGet);
}
The function needs to be of type JsonResult, and the returned value of Json using JsonRequestBehavior.AllowGet.
AngularJS:
$scope.fileList;
$http.get("/Home/GetFileList").then(function (result) {
console.log(result)
$scope.fileList = result.data;
})
This is in my AJS controller, using .then instead of .success. If you use console.log the result returned from the mvc controller and view it in the browser inspect you'll see the object with lots of other info and the values you want are in the .data section of the object.
So to access the values you need to do result.data. In my case this gives me and array. I assign this to a scope. Then in my view I can access the values by doing {{fileList[1]}} etc. This can also be used in ng-repeat e.g:
<div ng-repeat="file in fileList">
{{fileList[$index]}}
</div>
Each value in the array in the repeat can be accessed using $index which is the number of the repeat starting at 0.
I've a Web app with a button that makes a call to an API to refresh data:
[AcceptVerbs("GET")]
[Route("refreshFromService/{guid}")]
public HttpResponseMessage RefreshDataFromService(string guid)
{
if (!string.IsNullOrEmpty(guid) && guid.Length == 36 && new Guid(guid) == new Guid("C943F8E4-647D-4044-B19E-4D97FA38EDE0"))
{
new AdData().RefreshCacheAdData(true);
new JdeData().RefreshCacheJdeData(true);
return new HttpResponseMessage(HttpStatusCode.OK);
}
return new HttpResponseMessage(HttpStatusCode.Forbidden);
}
Actually, it's an AJAX call, so in my Network Tab in Google Chrome, I see the request is in pending for 5 minutes.
How can I make this method an async method and how can I refresh my UI to show progress?
EDIT
When I refresh the page, I want the Progress Status to be updated.
First of all, it has nothing to do with a backend. So solution to your problem lies on frontend site. Ajax are asynchronous by nature so you can do something like that.
const loader = document.createElement('span')
// some styles for the loader
// i'm using body just for example purposes
document.body.appendChild(loader)
fetch('refreshFromService/{guid}')
.then(data => {
document.body.removeChild(loader)
// do something with data
return data
})
You have to handle it on UI like this:
function getFlag() {
var option = {
url: '/controllerName/actionName',
data: JSON.stringify({}),
method: 'post',
dataType: 'json',
contentType: 'application/json;charset=utf-8'
};
$.ajax(option).success(function (data) {
$("#picture").append("<img id=\"img1\" src=" + data.img_path + "\ />");
});
};
I am using this code in UI for getting flags at runtime. So you need to write same type of code and get response from the backend.
url: '/controllerName/actionName' is the controller in MVC and then action implemented in that controller.
Request this method in UI with document.ready
I hope I have made sense to you. If still not clear write back i will explain further.
Cheers!
I'm working on an asp-mvc application and facing the following issue:
I have a model with simple properties plus one property which is a list of my custom object, and I render the Ienumerable property as mentioned here:
Passing IEnumerable property of model to controller post action- ASP MVC
In my view, I have a button that is supposed to add items to the ienumerable property of my model. Of Course, I don't want to lose already inserted data, so I need to pass the model to the corresponding action.
I've noticed that the model os transferred entirely only upon post. So, I did something like:
$(".addButton").click(function (event) {
event.preventDefault();
$("#FilterForm").submit();
#{ Session["fromAddFullItem"] = "true";}
return false;
});
And then in my controller, I do something like:
public ActionResult Index(FilterModel model)
{
if (Session["fromAddFullItem"].ToString() == "true")
{
Session["fromAddFullItem"] = "false";
return AddBlankItemTemplate(model);
}
I've read that assigning session in js is not recommended, but also tried TempData, and there the data was always null.
My problem is that Session["fromAddFullItem"] is always true, even when I come from another button. If I put breakpoint in addbtn click in line- Session["fromAddFullItem"] = "false";, and press the other button, I see that for some odd reason the mentioned breakpoint is hit, even though I haven't pressed the add button.
Any help? Maybe there is another way to achieve what I want. Currently, no matter which button I press (which posts the form), it comes as Session["fromAddFullItem"] = "false" and goes to action AddBlankItemTemplate. Thanks.
EDIT - AJAX POST
$(".addButton").click(function(event) {
event.preventDefault();
var modelData = JSON.stringify(window.Model);
$.ajax({
url: '#Url.Action("AddBlankItemTemplate")',
type: 'POST',
dataType: 'json',
data: modelData,
contentType: 'application/json; charset=utf-8',
});
return false;
});
and controller
public ActionResult AddBlankItemTemplate(string modelData)
EDIT 2:
$(".addButton").click(function (event) {
event.preventDefault();
$.ajax({
url: '#Url.Action("AddBlankItemTemplate")',
data: $("#FilterForm").serialize()
}).success(function(partialView) {
$('DetailsTemplates').append(partialView);
});
});
and Controller:
public ActionResult AddBlankItemTemplate(FilterModel model)
The line #{ Session["fromAddFullItem"] = "true";} is Razor code and will be run on page rendering and load regardless of where you put it in the page.
It's not client side code so won't wait for your js code to run. If you're trying to synchronise state between js and MVC have you looked into angularjs which could simplify these actions.
I have a query regarding an issue. As my application using Partial views and these partial views are loaded by ajax call and each partial view usage javascript and include js file, which eventually calls database to bind the data for that particular view.
Now, loading the view is taking more time than expected, as it loads js file and that js file makes another call to server to pull the records. I want my view to be loaded and then js file which makes db call to bind data. something like below -
If(partialview is loaded)
load js file , which will make ajax call and db eventually to bind data.
This will at least load the view and user will have something to see instead of waiting for blank background with loader.
Below is the script through which i am loading PartialView.
function loadview(action, hassubmenu, _fromtab) {
if (hassubmenu == 'true') {
return false;
}
if (!_fromtab) {
$('.process').show();
$('.mainbody').html('');
}
// call ajax to load view
$.ajax({
url: urlheader + "Home/LoadView/",
type: 'POST',
data: {
'view': action
},
success: function (data) {
// This outputs the result of the ajax request
$('.process').hide();
if (!_fromtab) {
$('.mainbody').html('').html(data);
// disable appfilter from start screen
var ostype = $('select#selection').find('option:selected').data('ostype');
var did = $('select#selection').find('option:selected').val();
if (ostype.toLowerCase() == 'ios' && action == 'Start') {
$('div.appfilter').hide();
$('#liAppFilter').hide();
}
getsyncinfo(did, false);
if (_currenttab != undefined) {
reloadCurrentFilterTab(_currenttab);
}
}
else
$('.chicoAppsUrlsDetails').html('').html(data);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
}
If I understand correctly, js events aren't firing for html inside your partial views (those of which are ajaxed)
This is because the html being loaded onto the page is coming after the js (which is binding your events).
You need to place any events on doms inside the partial view onto the document element instead with the jquery on method to specify a selector.
eg.
$(document).on('click', '.some-class', function(){
//do stuff
});
this way, you can add partials to the page with ajax and the doms within the partial will still fire events.
I have a mvc project, what I want to do is this:
I am sending an ajax request from my JS script. After processing it I want to redirect to a page with a model.
Now I tried sending a form as the ajax response and submit it like so:
sb.Append("<html>");
sb.AppendFormat(#"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>", "url..");
sb.AppendFormat("<input type='hidden' name='result' value='{0}'>", val1);
.....
And on the JS:
success: function (result) {
var form = $(result);
$(form).submit();
}
But this way i need to specify each post param, I want to send the entire model object.
How can I do that?
Edit
Full steps:
1.Using an MVC APP.
2.I submit button in my view which redirects the user to my JS code.
3.Js code sends an Ajax request to a MVC page called 'Transaction'.
4.C# code doing some actions and now I need to redirect the usr to a page named EOF with ALOT of post params, thats why I want to pass it as a ViewModel.
As you are using ajax, you could return the URL from your action and have it redirected in javascript:
Controller
public ActionResult Transaction()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("RedirectedAction") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (result) {
if (result.success == true)
{
window.location = result.redirecturl;
}
}
You can try this:
public ActionResult YourMethod(string param)
{
//what ever you want to do with reference no
return View("EOF");
// or, if you want to supply a model to EOF:
// return View("EOF", myModel);
}