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?

6
  • 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. Commented Sep 2, 2015 at 18:23
  • 2
    You need to learn about AJAX. Commented Sep 2, 2015 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. Commented Sep 2, 2015 at 18:33
  • @SLaks I am looking into AJAX now, thanks. Commented Sep 2, 2015 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? Commented Sep 2, 2015 at 18:35

2 Answers 2

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;
  }
});
Sign up to request clarification or add additional context in comments.

Comments

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/[email protected]

7 Comments

@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 - the MVC framework has some gotchas when it comes to handling JSON values.
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).
Yes, it makes perfect sense. Thanks again.
@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?
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.