0

I am working on project using MVC 3.0(Razor framework). I am trying to get values from controller to view using Viewdata on Button click in Javascript Method.Its coming on document.ready but not on Button click.So please help to get the viewdata value on button click.

Following is my code

     [HttpPost]
            public ActionResult Update()
            {
                ViewData["myInfo"] = "my info";
                return View();
             }

And my JAvascript code:

    <script type="text/javascript">
        $(document).ready(function () {
            $("#btn").click(function () {

                $.post("/ImportCSV/Update", {},
               function ()
                {
                var g = '@ViewData["myInfo"]';

                });
                });
                });
    </script>

I want to show Viewdata value on button click

1
  • 1
    your framing of question isn't understandable. Do you want to say that you are unable to pass data from an action method that is invoked by javascript code ??... Also post the related javascript code Commented Jan 3, 2012 at 13:41

1 Answer 1

2

You'd better return a JSON result in this case. ViewData is bad. Don't use it. In your case it doesn't work because you need to define a corresponding view of this controller action that will interpret the ViewData and it is the final HTML fragment that you will get in the AJAX success callback. Using JSON you can directly send some data to the calling script:

[HttpPost]
public ActionResult Update()
{
    return Json(new { myInfo = "my info" });
}

and then send an AJAX request to this controller action:

<script type="text/javascript">
    $(document).ready(function () {
        $("#btn").click(function () {
            var url = @Url.Action("Update", "ImportCSV");
            $.post(url, {}, function (result) {
                var myInfo = result.myInfo;
                alert(myInfo);
            });
        });
    });
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks alot but is there any way except JSON because i am already returning string related with rest of my functinality.pls suggest what to do
@user1004864, in this case JSON seems more adapted. As I already stated in my answer you could still use ViewData but you will have to define a corresponding Update.cshtml view. It is inside this view that you will get the contents of this ViewData that you set in the controller. And inside the AJAX success callback you will get the result of the rendering of this view.

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.