Question

i was putting my scripts in my view files (cshtml) when i started working with asp mvc3. i was doing it like this: at the bottom of each cshtml files, i put my scripts, .... and some of those scripts use TempData, everything works fine.

but then somebody told me that's its a bad habit to let users see how i code my scripts. they said that i should create a js file and put all my scripts in there and i should just call them like this:

 <script src="@Url.Content("~/Scripts/myOwnLocalScripts.js")" type="text/javascript"></script>.

so i did that but it seems that my scripts now cant read TempData and even session cookies. i have a line in my script like this:

 var currentEmployee = '@System.Web.HttpContext.Current.Session["UserNumber"]';
 $('.textBoxEmployeeNumber input[id="EmployeeId"]').val(currentEmployee);

it's supposed to display a user number but it is displaying "System.Web.HttpContext.Current.Session["UserNumber"]" as a string....

moreover, i have a code in my script like this:

  if ('@TempData["successMessage"]' != "" || '@TempData["successMessage"]' != null) {
    function newAlert(type, message) {
        $("#alert-area").append($("<div class='alert alert-success " + type + " fade in' data-alert><p><b> " + message + " </b></p></div>"));
        $(".alert-success").delay(4000).fadeOut("slow", function () { $(this).remove(); });
    }
    newAlert('success', '@TempData["successMessage"]');
}

it's supposed to be displayed only when Tempdata[successMessage] contains a value but it keeps displaying everytime the page loads and it is displaying '@TempData["successMessage"]' as a string...

what could be my errors?

Was it helpful?

Solution

The @... syntax is only interpreted server-side within Razor (.cshtml) files. In JavaScript (.js) files, the @ isn't special -- in this case, it's just another character in the string literals.

As for:

then somebody told me that's its a bad habit to let users see how i code my scripts

This is not an actual reason for separate .js files -- if the browser can read the JavaScript, the user can read it as well.

What they are actually useful for is allowing you to be DRY, defining common functions once for inclusion in multiple views, and for allowing the browser to cache the script while the view updates.

So, if these are common tasks, define functions for them in the .js that can be called from the .cshtml:

.js:

function setCurrentEmployee(currentEmployee) {
    $('#EmployeeId').val(currentEmployee);
}

function newAlert(type, message) {
    if (message != "" || message != null) {
        $("#alert-area").append($("<div class='alert alert-success " + type + " fade in' data-alert><p><b> " + message + " </b></p></div>"));
        $(".alert-success").delay(4000).fadeOut("slow", function () { $(this).remove(); });
    }
}

.cshtml:

<script>
    setCurrentEmployee('@System.Web.HttpContext.Current.Session["UserNumber"]');
    newAlert('success', '@TempData["successMessage"]');
</script>

OTHER TIPS

If you don't want to use inline javascript in your cshtml, use JavaScriptModel ( http://jsm.codeplex.com ).

You would just have to write the following code in your controller action:

this.AddJavaScriptVariable("CurrentEmployee", System.Web.HttpContext.Current.Session["UserNumber"]);
this.AddJavaScriptVariable("SuccessMessage", successMessage);
this.AddJavaScriptFunction("ReadyFunction");

.js:

var CurrentEmployee;
var SuccessMessage;
function ReadyFunction()
{
    setCurrentEmployee(CurrentEmployee);
    newAlert("success" SuccessMessage);
}

Alternatively you could also write the following code in your controller action:

this.AddJavaScriptFunction("setCurrentEmployee", System.Web.HttpContext.Current.Session["UserNumber"]);
this.AddJavaScriptFunction("newAlert", "success", successMessage);

But I would recommend you the first solution since you could reuse the currentEmployee elsewhere in your javascript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top