1

I've got an Ajax.BeginForm on my page which on success should run a javascript function. I've done that before and it has worked fine. However, in today's case I want to pass in my javascript function some variables that I get from my ViewModel:

My partial view:

@model MyProject.ViewModels.CategoryViewModel

@{
    var hasLang = Model.Language != "" ? Model.Language : "-1";
}


<script type="text/javascript">

function UpdateCategoryProgress() {
    console.log("this works");
    console.log(@hasLang);
    console.log("this doesn't works");
    if (@hasLang == "-1") {
        $.post('@Url.Action("CategoryProgress", "Home")', { categoryid: @(Model.Category.Id) }, function (data) {
            populateDiv($("#CategoryProgressWrapper"), data);
        });
    }
    else {
        $.post('@Url.Action("CategoryProgress", "Home")', { categoryid: @(Model.Category.Id), lang: @(hasLang) }, function (data) 
            populateDiv($("#CategoryProgressWrapper"), data);
        });
    }
}
</script>

<div id="editingContainer">
@using (Ajax.BeginForm("Edit", new AjaxOptions { UpdateTargetId = "featuresDiv", OnSuccess = "UpdateCategoryProgress" }))
{
 (code here)
)

Now to the interesting part, the code runs fine. The function is run on success however only the first console.log("this works") is displayed in the console. Everything after that is simply ignored.

I've tried using the hasLang variable because when I was running the following:

if (@Model.Language == "") {
    $.post('@Url.Action("CategoryProgress", "Home")', { categoryid: @(Model.Category.Id) }, function (data) {
        populateDiv($("#CategoryProgressWrapper"), data);
    });
}
else {
    $.post('@Url.Action("CategoryProgress", "Home")', { categoryid: @(Model.Category.Id), lang: @Model.Language }, function (data) {
        populateDiv($("#CategoryProgressWrapper"), data);
    });
}

I would get the error in the firebug console:

syntax error
if ( == "")

It was completely ignoring the @Model.Language

I've also tried passing the it with () like: @(hasLang) or @(@Model.Language) without success.

How can I pass my @Model.Language to my jquery?

Thanks

1 Answer 1

2

You need to put Model.Language in double-quotes to create a Javascript string literal.

You should also call Server.JavaScriptStringEncode.

Sign up to request clarification or add additional context in comments.

2 Comments

Geez... I even do that on another one of my pages... how could I not notice this. Thanks! However, why call the @Server.JavaScriptStringEncode for?
@Lan: In case the string has a " or a newline. Otherwise, you'll have an XSS hole.

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.