0

I want to access view data In Java script in following code

public virtual ActionResult Edit(MyModel _MyModel)
{
    //some Code

    if (true..)
    {
            ViewData["Messages"] = "Data Updated Sucessfully";
    }
        else
    {
        ViewData["Messages"] = "you cannot Updated data";
    }

    return View();
}

In javascript

function SaveData() {
    $("#btnSave").click(function () {
        //          $('#divLoadImage').show();
        //            $('#divOverlay').show();
        //   debugger;
        $.ajax({
            type: "POST",
            url: "Admin/Edit/",
            data: "",
            complete: function () {
                alert(ViewData["Messages"]);
            }
        });
    });
}

it give me no value in alert..

1
  • I don't understand what you are asking, also can you try to format your code better? Commented Apr 3, 2011 at 10:21

1 Answer 1

4

You need to encode it using for example the JavaScriptSerializer class:

function SaveData() {
    $("#btnSave").click(function () {
        $.ajax({
            type: "POST",
            url: "Admin/Edit/",
            data: "",
            complete: function () {
                alert(@Html.Raw(new JavaScriptSerializer().Serialize(ViewData["Messages"])));
            }
        });

    });
}

or use simple quotes but be careful as this might break if the message contains quote so I wouldn't recommend you this:

alert('@ViewData["Messages"]');
Sign up to request clarification or add additional context in comments.

Comments

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.