Saturday, November 1, 2014

Return JavaScriptResult in controller MVC

JavaScriptResult Sends JavaScript content to the response because it couples Controller and View back together to make them dependable on each other. Here we see how to use a JavaScript result in controller in MVC as shown below
In this example we have updated the time on shown in div when I click on actionlink mvc. In other words we have says that the GetData result method we get a div element and update its content using JavaScript
So first we have create method in controller named “Getdata()” as you seen below it
  [HttpGet]
        public JavaScriptResult GetData()
        {
            string jsData = @" $('#updateTime').html('" + DateTime.Now.ToLocalTime() + ')";
            return JavaScript(jsData);
        }
On razorhtml page
<div id="updateTime"> </div>

@Ajax.ActionLink("Get Updated time server""GetData","Home"new AjaxOptions { HttpMethod="GET",InsertionMode =InsertionMode.Replace,OnComplete="CompletedTask",UpdateTargetId="updateTime" });


<script type="text/javascript">
    function CompletedTask()
    {
        alert("task completed");
    }
   
    
</script>
It this code needs to work you have to include jquery and ajax library
  <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

No comments:

Post a Comment

http://blogsiteslist.com