Thursday 4 July 2013

Return Type in MVC3 ActionResult

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() {   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(urldatafunction (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(nameJsonRequestBehavior.AllowGet);
        }

Now run your Application: Enter ID in textbox and click on Get Name Button and see output.

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives