1

I found similar questions to mine, but in all of those examples, the variable was part of the model. I am trying to pass a variable that is created in javascript, which is not part of the model.

Code:

 $(document).ready(function () {

    var url = document.URL;
    var index = url.indexOf("?email=");
    var email;

    /* If there is an EMAIL in URL, check directory to confirm it's valid   */
    if (index > -1) {
        /* There is an email */
        email = url.substr((index + 7));
        email = email.substr(0, (email.length - 4)) + "@@mymail.ca";

        /* Check directory to see if this email exists */
        @Html.Action("CheckDirectory", "Home", new { email = ???});

    }
});

Is there a way to fill in the ??? with the email above?

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
Uğur Dinç
  • 2,415
  • 1
  • 18
  • 25
  • That use of `@Html.Action()` doesn't make any sense. It would produce a syntax error in the client-side JavaScript. As for "passing a value", you can update the client-side markup with JavaScript. So if there's something to be posted to a controller then you can set it on a URL in the markup or set a form element's value for a form post. Or perhaps you want to make an AJAX request to a controller method to perform some operation? It's really not clear what you're even trying to do here. – David Sep 02 '15 at 18:23
  • 2
    You need to learn about AJAX. – SLaks Sep 02 '15 at 18:23
  • @David I have a Kendo Scheduler on this view, which will allow people to create bookings if they have a valid account. To check the directory of accounts, I have to navigate to an external URL to webscrape list of emails (account Ids). So before I load the scheduler, I am trying to call "CheckDirectory" in Home controller to verify whether email is valid or not. – Uğur Dinç Sep 02 '15 at 18:33
  • @SLaks I am looking into AJAX now, thanks. – Uğur Dinç Sep 02 '15 at 18:35
  • Are you trying to redirect the current page to /home/checkdirectory, or call an ajax function and doing something with the result? – Tieson T. Sep 02 '15 at 18:35
  • @TiesonT. call an ajax function and doing something with the result.... – Uğur Dinç Sep 02 '15 at 18:36

2 Answers2

3

You can pass your value as a GET parameter in the controller URL:

$(document).ready(function () {

  var url = document.URL;
  var index = url.indexOf("?email=");
  var email;

  /* If there is an EMAIL in URL, check directory to confirm it's valid   */
  if (index > -1) {
    /* There is an email */
    email = url.substr((index + 7));
    email = email.substr(0, (email.length - 4)) + "@@mymail.ca";

    /* Check directory to see if this email exists */
    window.location.href = '/CheckDirectory/Home?email=' + email;
  }
});
Peter Gluck
  • 8,168
  • 1
  • 38
  • 37
1

To answer your question of

Is there a way to fill in the ??? with the email above?

No. The Razor code is similar to, say, PHP, or any other server-side templating language - it's evaluated on the server before the response is sent. So, if you had something like

@Url.Action("checkdirectory", "home")

in your script, assuming it's directly in a view, it would get replaced by a generated URL, like

/home/checkdirectory

Your code, which uses

@Html.Action("checkdirectory", "home")

actually executes a separate action, and injects the response as a string into the view where it's called. Probably not what you were intending.

So, let's try to get you on the right path. Assuming your controller action looks something like

[HttpGet]
public ActionResult CheckDirectory(string email = "")
{
    bool exists = false;

    if(!string.IsNullOrWhiteSpace(email))
    {
        exists = YourCodeToVerifyEmail(email);
    }

    return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}

You could, using jQuery (because XMLHttpRequests are not fun to normalize), do something like

$(function(){

    var url = '@Url.Action("checkdirectory", "home")';

    var data = { email : $('#email').val() };

    $.get(url, data)
        .done(function(response, status, jqxhr) {  

            if(response.exists === true) {
                /* your "email exists" action */
            }
            else {
                /* your "email doesn't exist" action */
            }

        })
        .fail(function(jqxhr, status, errorThrown) { 
            /* do something when request errors */
        });

});

This assumes you have an <input /> element with an id of email. Adjust accordingly. Also, the Url helper can only be used within a view; if you're doing this in a separate JavaScript file, replace it with a hard-coded string (or whatever else works for you).

Edit:

Since it seems I didn't entirely get what you were trying to do, here's an example of returning a different view based on the "type" of user:

public ActionResult ScheduleMe(string email = "")
{
    if(!string.IsNullOrWhiteSpace(email))
    {
        ActionResult response = null;
        var userType = YourCodeToVerifyEmail(email);

        // Assuming userType would be strings like below
        switch(userType)
        {
            case "STAFF":
                response = View("StaffScheduler");
                break;

            case "STUDENT":
                response = View("StudentScheduler");
                break;

            default:
                response = View("ReadOnlyScheduler");
                break;
        }

        return response;
    }

    return View("NoEmail");
}

This assumes you would have 4 possible views: the three you mentioned, plus an "error" view when no email parameter was given (you could also handle that by redirecting to another action). This variation also assumes a user has somehow navigated to something like hxxp://yourdomain.tld/home/scheduleme?email=peter@innotech.com

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
  • @UğurDinç Do the explanations make sense? Also, you'll want to do some reading on [why `JsonRequestBehavior.AllowGet` was required for the action result](http://stackoverflow.com/questions/8464677/why-is-jsonrequestbehavior-needed) - the MVC framework has some gotchas when it comes to handling JSON values. – Tieson T. Sep 02 '15 at 21:07
  • The new problem is that the response comes (~5)seconds after the View loads, whereas the view should have been dependent on the response. I.e if the email belongs to STAFF, load Staff Scheduler (no restrictions), else if the email belongs to STUDENT, load Student Scheduler (restricted use), else, load View Scheduler only (non-editable). – Uğur Dinç Sep 02 '15 at 21:07
  • Yes, it makes perfect sense. Thanks again. – Uğur Dinç Sep 02 '15 at 21:09
  • @UğurDinç That sounds like something you can/should handle on the server. This code assumes you were at an existing action, and wanted to check an email. If you simply want to show a different view based on a paramater passed to the action, you'd handle that before returning the response. Where is the email coming from? – Tieson T. Sep 02 '15 at 21:11
  • Basically, I am receiving an email address (encoded) in the URL (?email=mymail) for every person visiting the application. I need to verify whether this email exists in the directory. This is where the "checkDirectory" comes in. CheckDirectory in the controller goes to a page somewhere on the web, and checks whether the email of this person is good or not. Then depending on the result and type of email (staff vs student), I need to load one of the schedulers. – Uğur Dinç Sep 02 '15 at 21:26
  • @UğurDinç That sounds like you either would use this version (with perhaps a loading animation) and return a PartialView instead of a JSON result, or handle it entirely on the server. I will edit an example of the second option into the answer. – Tieson T. Sep 02 '15 at 21:31
  • Thanks a lot once again. Given the restricted circumstances I am in, I was trying to avoid having multiple views, but I think I will go in that direction after all. And during the 5 second wait, I will show "Redirecting" on a blank view. – Uğur Dinç Sep 02 '15 at 22:05