views:

64

answers:

1

I am trying to add ASP.NET MVC features(Especially Routing) to my already existing ASP.NET Web application.I added a Controlled and View (an asp.net page) .Now i want to know how can i display the details of object of my custom class( Ex : User) in the view ? Can assign the object in ViewData collection and render it in the view ? Hows that ? I already have a Datalayer (in ADO.NET) which is running for the the current ASP.NET web app.So i want to use that.

I tried this in my controller

public ActionResult Index()
    {
        BusinessObject.User objUser = new BusinessObject.User();
        objUser.EmailId = "[email protected]";
        objUser.ProfileTitle = "Web developer with 6 yrs expereince";

        ViewData["objUser"] = objUser;
        ViewData["Message"] = "This is ASP.NET MVC!";

        return View();
    }

How can i use this in the view page to display the user details ?

Thanks in advance

+1  A: 

You should pass your object as a view model (or part of a view model, along with your message) to a strongly-typed view. Then you can simply reference the model properties in your view.

public class IndexViewModel
{
    public BusinessObject.User User { get; set; }
    public string Message { get; set; }
}

(or, better yet, just the properties from the user object that you really need)

Controller

public ActionResult Index()
{
    BusinessObject.User objUser = new BusinessObject.User();
    objUser.EmailId = "[email protected]";
    objUser.ProfileTitle = "Web developer with 6 yrs expereince";

    return View( new IndexViewModel {
         User = objUser,
         Message = "This is ASP.NET MVC!";
    });
}

View

<%@ Page Title="" Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.MVC.ViewPage<MyWebSite.Models.IndexViewModel>" %>

<%= Html.Encode( Model.User.EmailId ) %>
tvanfosson
What does this Inherits="System.Web.MVC.ViewPage<MyWebSite.Models.IndexViewModel>" means ?
Shyju
@shyju - It means that the ViewPage's Model property is of type `MyWebSite.Models.IndexViewModel` -- the namespace is fake, but is meant to correpsond with the model class in the example.
tvanfosson

related questions