Thursday, 4 July 2013

Return Type in MVC3 ActionResult


Suggestion If you are not familiar with ASP.NET MVC yet, well, this post is not for you :-) 
Most action methods return an instance of a class that derives from ActionResult. The ActionResult class is the base for all action results. However, there are different action result types, depending on the task that the action method is performing. For example, the most common action is to call the View method. The View method returns an instance of the ViewResult class, which is derived from ActionResult.
You can create action methods that return an object of any type, such as a string, an integer, or a Boolean value. These return types are wrapped in an appropriate ActionResult type before they are rendered to the response stream.
The following table shows the built-in action result types and the action helper methods that return them.
Action Result
Helper Method
Description
Renders a view as a Web page.
Renders a partial view, which defines a section of a view that can be rendered inside another view.
Redirects to another action method by using its URL.
Redirects to another action method.
Returns a user-defined content type.
Returns a serialized JSON object.
Returns a script that can be executed on the client.
Returns binary output to write to the response.
(None)
Represents a return value that is used if the action method must return a null result (void).

Marking Public Methods as Non-Action Methods

By default, the MVC framework treats all public methods of a controller class as action methods. If your controller class contains a public method and you do not want it to be an action method, you must mark that method with the NonActionAttribute attribute.
The following example shows a method that is marked with the NonAction attribute.
   [NonAction]
   private void DoSomething()
   {
    // Method logic.
   }
>->->----------------------------------------------------------------->>
using ContentResult
First, create a new MVC project in visual studio (I'm using ASP.NET MVC 3 on framework 4.0 / VS 2010):Add this action method below the "Index" method in HomeController Class:
public ContentResult GetServerTime() {  return Content(DateTime.Now.ToShortDateString()+ " " + DateTime.Now.ToShortTimeString()); }
The method returns the current server's date & time.  Now, copy and paste this code to your view file (Index.aspx): <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Index</title>
    <script src="/Scripts/jquery-1.4.1.min.js" 
        type="text/javascript"></script>
</head>
<body>
    <div>
        <div id="div1"></div>
    </div>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: "/Home/GetServerTime",
                success: function (data) {
                    $("#div1").html(data);
                }
            });
        });
    </script>
</body>
</html>
now Run your Application. it'll display Current DataTime.
>->->----------------------------------------------------------------->>
using JsonResult
Now, copy and paste this code to your view file (Index.chtml):
<p><input type="text" id="userid" /><input type="button" value="Get Name" id="btn2" /></p>
<br /><div><span id="resultMessage"></span></div>
Add Script-
<script>
 $(function ()
 {
       $("#btn2").click(function () {
            var text = $("#userid").val();
            var url = '@Url.Action("getName", "User")';
            var data = { UID: text };
            $.post(url, data, function (result) {
                var message = result;
               $("#resultMessage").text(message);
            });
       });
    });
    </script>
now add the Action Method in UserController Class
       public JsonResult getName(int UID)
{
           string name = null;
           if(UID == 1)
            { name="suraj";}
            else
            { name = "Mad"; }
            return Json(name, JsonRequestBehavior.AllowGet);
        }
Now run your Application: Enter ID in textbox and click on Get Name Button and see output.

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (9) Web Service (1) XMl (1)