software
software

Reputation: 728

How do I return an integer to a View in ASP.NET MVC?

In the following code I'm trying to return a view with an integer as its type. The code below doesn't work. What am I missing?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication5.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index(int answer)
        {


           int row = 2;
           int col = 1; 

           answer = row * col ; 
           return View(answer);
        }

    }
}

Upvotes: 2

Views: 7217

Answers (4)

Kim Tranjan
Kim Tranjan

Reputation: 4541

As I can see, you're trying to open the URL http://localhost:8080/Home/Index and the problem is that the action "Index" have a parameter called answer.

Try to call http://localhost:8080/Home/Index?answer=10 and you'll see that it will work.

edit:

as Darin said, make sure that the Index.aspx exists.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

public ActionResult Index(int answer)
{
    int row = 2;
    int col = 1; 
    int answer = row * col ; 
    return View(answer);
}

and then ensure your view is strongly typed to int:

<%@ Page 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<int>" 
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    The answer is: <em><%= Html.DisplayForModel() %></em>
</asp:Content>

Upvotes: 4

John Bledsoe
John Bledsoe

Reputation: 17642

You're likely requesting the action URL without specifying an answer parameter. Change your method signature to the following and it should all work:

public ActionResult Index()

Upvotes: 0

smartcaveman
smartcaveman

Reputation: 42246

There is nothing wrong with the code you posted.

The error must be related to something else.

If you want to know the cause of the error it would help to indicate what error you are receiving, as well as stack information.

Upvotes: 0

Related Questions