Saturday, January 11, 2014

Calling a Controller method from UI

In this post, I will talk about accessing a method in Controller and displaying the returned data inside a div tag.

I am displaying a scenario here, where I would like to retrieve logged in user id from a controller method and to display the same within the div tag.

In my sampleview.cshtml

Logged in user : <div id="username"></div>
Below is the ajax code, that will invoke a method (GetUserName) from my controller and on successful retrieval, it can be read at the success event. I had used an alert to identify the successful event return for data.

  You can even load this inside a button click event, if you want the data to appear conditionally.

<script>
var url = '@Url.Action("GetUserName","Home")';
        $.ajax({
            url: url,
            type: 'GET',
            success: function (data) {
                alert("data returned");
                $("#username").html(data);
            }
        });
</script>

   In the above case, returned data will be displayed as HTML content within the div tag "username"

Now lets take a closer look at the controller method that will return the string to be displayed in view.

Controller:
public class UserName : Controller
{
        public string GetUserName()
       {
             // Data access code goes here...
             return stringvalue;
        }
}

  I was debugging a code similar to the above for drop down change event and discovered that my calls are working only for the first time and it did not hit my debugger inside GetUserName for the rest of my attempts. Though it was confusing initially, it took a while, before I realized that I was missing cache specific statement, which defines if the call needs to be made every time it is invoked or to re-use cached data.

 Below is the final script, that can be used to invoke for every change/click event.

<script>
var url = '@Url.Action("GetUserName","Home")';
        $.ajax({
            url: url,
            type: 'GET',
            cache : false,
            success: function (data) {
                alert("data returned");
                $("#divid1").html(data);
            }
        });

</script>