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
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>