I want to call a javascript function from within a controller function that I use:
Public Function redirectTo() As JavaScriptResult
Return JavaScript("ToSignUp()")
End Function
in my controller. But the program never goes to the script. I've already checked similar answers but I haven't found any solution to the problem. Can someone assist me with this?
ADDITION 4/3/19 12:41
I use the following for redirection from my controller... but nothing is happening:
Public Function redirectTo() As RedirectToRouteResult
Dim routes As New RouteCollection With {.RouteExistingFiles = True}
Return RedirectToAction("../login/SignUp")
End Function
End Class
ADDITION 4/3/19 23:20
The issue was solved by this way
In the code behind of my .aspx Page and at the proper place I add it the following code:
Dim routes As New RouteCollection With {.RouteExistingFiles = True}
Response.Redirect("SignUp")
The Response.Redirect instruction is not new.
But in order to be functional it needs to add before the following instruction
Dim routes As New RouteCollection With {.RouteExistingFiles = True}
And that is because the MVC did not recognize the existent files which means the property RouteExistingFiles is always False
Thus in order to work the code we need to turn this property to True
Anyway thanks to all for your assistance.
From other examples online (like this one), I would say that if you temporarily changed your function to:
Public Function redirectTo() As JavaScriptResult
Return JavaScript("alert("HERE");")
End Function
It will likely work... so without seeing the JS function contents, it's hard to tell. To the second point, a RedirectToAction call will work if called from the server; if the client is calling this, use 'window.location' instead.
Related
All,
I have the following route/action defined on my controller :
[RoutePrefix("widgets/download-functions")]
[Route("download/{publishedReportId}"), HttpGet]
public ActionResult Download(int publishedReportId)
And inside my js code, I want to create some routing with the appropriate id.
This is what I have inside my js code (which doesn't work). What am I missing?
self.downloadFile = function (data) {
console.log(data);
console.log("#(Url.Action("Download", new { publishedReportId = 9999 }))");
console.log("#(Url.Action("Download"))");
};
Still new to this stuff and learning, I am sure it is something simple.
When I run this code, I get the following in the console
Console output
Thx
jonpfl
If you are using Url.Action, it doesn't take advantage of attribute routing, you will need to follow the original method of routing, which is to use, Action, Controller, area and params to get the extension method to produce the url.
[RoutePrefix("widgets/download-functions")]
public class WidgetDownloadController : Controller
...
[Route("download/{publishedReportId}"), HttpGet]
public ActionResult Download(int publishedReportId)
You would get a Url.Action like:
console.log("#(Url.Action("Download","WidgetDownload", new { publishedReportId = 9999 }))");
Also, this will only work on scripts that are parsed by the razor engine, ie. scripts that are written directly in the view.
I need to do something seemingly quite simple.
In the same way that I can, from my scala.html file, create a link to another url, /entry, I need to do that from a javascript file.
i.e., from the scala.html:
<div class="footer">
<a href='#routes.Application.index()'>Home</a>
</div>
from my javascript event:
function() myEvent {
window.location="#routes.Application.entry()"; // DOESN'T WORK!
}
For routing from javascript, I've already had to setup my javascript routes for some ajax work I've already had to do.
My ajax work was calling a method 'findPersons()' so in my Application.java file, I had already:
public Result jsRoutes()
{
response().setContentType("text/javascript");
return ok(Routes.javascriptRouter( "appRoutes",
routes.javascript.Application.findPersons()));
}
Because I want to be able to redirect to my GET entry() method, I modified it to look like this:
public Result jsRoutes()
{
response().setContentType("text/javascript");
return ok(Routes.javascriptRouter( "appRoutes",
routes.javascript.Application.findPersons(),
routes.javascript.Application.entry()));
}
Additionally I have these in my routes file:
GET /entry controllers.Application.entry()
POST /findPersons controllers.Application.findPersons()
When I am invoking my findPersons method, it is really nice and simple.
It looks like this:
appRoutes.controllers.Application.findPersons().ajax({
data: {
personIdentifier : personIdentifier,
surname : surname,
givenNames : givenNames
},
success : processDBQuery
});
For my simple redirect, I would like to be able to maintain the same loose coupling between my html/javascript code and the urls, as I can the ajax call above.
My redirect needs to occur on an event. Therefore, the easiest and quickest solution would have been simple to write:
function() myEvent {
window.location="/entry";
}
However, then I would be hard-coding the URL (which I have managed to avoid for my ajax call above), no longer maintaining that loose coupling I would so much like to have.
However, I see no examples in the documentation, and from what I have in the generated javascript (for my routes) there is no chance.
Is there any way to achieve what I am after?
thanks for reading!
p.s., I should add; I guess I have also thought of the possibility of using the ajax call that is generated, I guess I can probably fetch the page I want... and there is probably a means of replacing the current document with the entire content of the fetched page. but that just sounds bad.... wrong...
or not?
I was rather hoping for a substitution, as is done in my html
i.e, my link as shown above is generated to look like this:
<div class="footer">
<a href='/'>Home</a>
</div>
In the same way, I hoped there was some means of substitution in the javascript, so that the event function above ends up in being massaged into looking like this:
function() myEvent {
window.location="/entry";
}
Jacques, from the above comments, helped me to realize a work-around.
From within my "assets located" javascript file, I can still refer to page/template located javascript.
Own-file/assets located javascript doesn't seem to be transformed how I expected.
However, Page/template located javascript is transformed exactly how I require.
I can refer to a template located javascript function from my assets located javascript.
This means, I have a little work-around of one extra little function inside the template which does the redirection for me.
i.e.,
myJavascript.js:
function personResultsListClickHandler(personId) {
var fpersonId = personId;
return function() {
window.alert("hello! " + fpersonId);
affectRedirect();
};
}
myTemplate.scala.html
#main("person lookup") {
<script type="text/javascript">
function affectRedirect(){
window.location="#routes.Application.entry()";
} // Need this here so it will be transformed.
// asset located javascript doesn't seem to get transformed like javascript here in template! :(...
</script>
Another possibility is the fact that the Javascript object retrieved by calling:
appRoutes.controllers.Application.entry()
contains a url member. This url member is exactly what I can use to assign to window.location. However, it looks a bit unofficial.. in terms of
1. the member not being documented
2. not sure if the url member will exist in the future
3. the generated javascript is constructing an object dealing with ajax... and i'm just grabbing the URL member from it... it just feels... like a hack.
But i've tested this, and it works. See code below:
function patientResultsListClickHandler(personId) {
var fpersonId = personId;
return function() {
window.location=appRoutes.controllers.Application.entry(personId).url;
// window.location="/entry/" + fpersonId; // the sort of hard-coding of URL that
}; // I wanted to avoid, but don't seem able to.
}
Does anyone else have a better solution?
I've been working on a HTML helper which will hide or show menu items depending on what type of user you are.
For this reason, In one of my controllers I am setting a session variables with values such as "ADMIN"
context.Session["perfil"] = "ADMIN"
The problem I am facing is that the Helper function is being called before the Javascript function which calls the controller that sets the session variables
This is how I call my HtmlHelper (through Razor)
#using XSiteManagerWeb.Helpers
#Html.Raw(Html.MiMenu("../Home/Configuracion", "Configuración"))
From my _Layout.cshtml
But before doing that I'm calling the function
<script type="text/javascript">ObtenerDatosSesion();</script>
Which calls a Controler method through Ajax
...
$.ajax({
url: "../Home/ObtenerDatosSesion",
....
Question: Why is the HtmlHelper being called before ObtenerDatosSesion(); even though I've put it before on the _Layout.cshtml ?
I've also tried calling in on window load doing this:
<body class="Fondoblue" onload="ObtenerDatosSesion();">
among other methods.
I noticed the Helper is being called before everytime after many debuggings. What I can't figure out is why that happens.
I wonder if it has anything to do with the Web.config line one has to put to use html helpers
<add namespace="XSiteManagerWeb.Helpers"/>
So to make it clear, I just want to make my "ObtenerDatosSesion(); method gets called before my html helper!
The razor helpers are executed server side, therefore they will be executed before any JS is rendered/executed on the page.
I would recommend moving whatever logic is in your ../Home/ObtenerDatosSesion endpoint to the same endpoint as ../Home/Configuracion. If it's going to be called more than once, you can put it in its own method.
So, recently I've been trying to call a controller action via javascript $.get. I was suggested by a fellow Stack Overflow member to use
$.get("custom/balance", function(){ });
Where custom is the name of the controller that I am using and balance is actionBalance()—a function that I have declared inside of that controller. I have tried to do so but it seems that the function is not being called. I have placed intentional errors inside of that function so I am sure it is not being called via the $.get function.
previously, I had directed $.get to a file in assets like so
$.get("assets/balance.php, function() { });
This had worked perfectly.
Finally, here is the actionBalance that I have declared - is it possible that I need to then call that function? I'm not sure why custom/balance is not calling the action itself.
public function actionBalance() {
// Return a string
echo '7000';
}
I apologize for the previously incomplete answer which left you confused, as I assumed everyone would want to remove the index.php script name from the URL.
If you are using the default settings, yes, you should add the index.php?r= before the path. index.php is called the entry script in Yii. Other files are hidden/protected from the public in the protected folder.
To hide this entry script from the URL, please follow this tutorial on Yii's website:
Yii 1.1: Url: hide index.php
I'm going round in circles and can't seem to figure out a solution from the resources currently available here on Stack or Google. There's got to be something obvious that I'm missing, perhaps you might be able to help?
Story summary:
A javascript function launches when clicked and creates a new contact in our database.
Additional functions are then called upon successful creation to toggle some settings where necessary, dependant on a few checkboxes.
Calls are currently being made asynchronously, resulting in only the last function call to successfully update the contact.
I can't, for the life of me, get the call to work one after the other instead.
Each call returns a JsonResult upon successful completion, if that helps at all (needed for other areas of the application.
Code currently looks like:
function CreateClicked(){
Contact.Create(**bunch of params**, function(data){
if(data.success) {
togglePrimary(data.newId);
toggleBilling(data.newId);
toggleTechnical(data.newId);
toggleBalance(data.newId);
toggleSecurity(data.newId);
toggleMarketing(data.newId);
Modal.Load(**loads a modal view**);
}
}
}
The toggle functions then look like:
function togglePrimary(id) {
if ($("#contact_admin_primaryrole").prop('checked'))
{Contact.TogglePrimaryRole(id);}
}
Which calls a controller function that looks like this:
public JsonResult TogglePrimaryRole(int contactId){
try{
var c = new Contact(contactId);
c.IsPrimaryContact = !c.IsPrimaryContact;
c.Update(AuthenticatedUser.Username, !c.IsPrimaryContact);
return Json(JSONResponseFactory.SuccessResponse("Contact updated successfully"));
}
catch (Exception ex){
return Json(JSONResponseFactory.ErrorResponse(ex.Message));
}
}
How should I go about setting this up so that each toggle function doesn't start until the previous one has finished and returned a Json response, regardless of success?
Any ideas?
Cheers,
Dez
Using jQuery promises should help:
togglePrimary(data.newId).then(toggleBilling(data.newId)).then(toggleTechnical(data.newId)
etc.
This will run the next function only if the last one was a success. If you want to call the function irrelevent of the outcome then use always() instead of then()
togglePrimary(data.newId).always(toggleBilling(data.newId)).always(toggleTechnical(data.newId)
This will require jquery 1.6 or higher to be referenced. To reference from the CDN add the following
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
I couldn't seem to get anywhere with promises, or javascript function chaining with callbacks... so I turned the values of each status into an array of strings and parsed it within the controller instead!
Thanks for helping :)