leora
leora

Reputation: 196861

asp.net-mvc is it possible to get ViewData and stick it inside javascript function

i have the following javascript that gets HTML from somewhere and sticks it in a textarea for tinymce.

My question is how in asp.net-mvc i can get the HTML Here and stick it in the javascript?

Do i put this in ViewData?

function ajaxLoad() {
        var ed = tinyMCE.get('elm1');
        // Do you ajax call here, window.setTimeout fakes ajax call
        ed.setProgressState(1); // Show progress
        window.setTimeout(function() {
            ed.setProgressState(0); // Hide progress
            ed.setContent('HTML Here');
        }, 500);
    }

i want to have something like this below, but it doesn't seem to work:

function ajaxLoad() {
        var ed = tinyMCE.get('elm1');
        // Do you ajax call here, window.setTimeout fakes ajax call
        ed.setProgressState(1); // Show progress
        window.setTimeout(function() {
            ed.setProgressState(0); // Hide progress
            ed.setContent(<% ViewData["test"] %>);
        }, 500);
    }

Upvotes: 1

Views: 3436

Answers (3)

sirrocco
sirrocco

Reputation: 8055

If you're in an aspx or ascx page then you can do that exactly like in your example - with one minor change :

ed.setContent(<%= ViewData["test"] %>); // the equals sign

If you're in a *.js file then that won't work, but you could set

<input type="hidden" id="myTestData" value='<%=ViewData["test"]%>' />

in the aspx,ascx file and then get the value via jQuery:

$("#myTestData").val();

Edit: damn, I missed the ending %> on the <input line.

Upvotes: 3

nkirkes
nkirkes

Reputation: 2665

I think an ajax call might suit you best, but also make sure you're trying <%= ViewData["test"], note the "=" after that first percent symbol. The example you gave won't emit the value of the ViewData field the way you have it there (maybe that was just a typo?).

Upvotes: 5

griegs
griegs

Reputation: 22770

I use this;

In my view;

$.post("/jQueryTests/jQueryAddMessageComment", { commentText: commentText }, function(newComment) {
            $("#divComments" + id.toString()).html(newComment);
        });

Of if I am returning Json data then;

$.post("/Articles/jQueryDownVoteArticle", { id: id }, function(votes) { document.getElementById("ArticleVotes").innerHTML = votes; }, "json");

In my controller;

return PartialView("commentList", new FormViewModel { LastComment = commentText });

The important bit is how you return back to the view. You can also return like this;

return Json(new FormViewModel { LastComment = commentText });

Remember that the control you are replacing the html for needs to have a unique id.

Is this what you asked?

Upvotes: 0

Related Questions