Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 2 如何使用ASP.NET MVC在查看页面中显示自定义对象属性?_Asp.net Mvc 2_Controller - Fatal编程技术网

Asp.net mvc 2 如何使用ASP.NET MVC在查看页面中显示自定义对象属性?

Asp.net mvc 2 如何使用ASP.NET MVC在查看页面中显示自定义对象属性?,asp.net-mvc-2,controller,Asp.net Mvc 2,Controller,我正在尝试将ASP.NET MVC功能(尤其是路由)添加到我已经存在的ASP.NET web应用程序中。我添加了一个控制器和视图(asp.net页面) 现在我想知道如何在视图中显示自定义类的对象(例如,用户)的详细信息?我可以在ViewData collection中指定对象并在视图中渲染它吗?我已经有一个数据层(在ADO.NET中)正在为当前的ASP.NET web应用程序运行,所以我想使用它 我在我的控制器上试过这个 public ActionResult Index() {

我正在尝试将ASP.NET MVC功能(尤其是路由)添加到我已经存在的ASP.NET web应用程序中。我添加了一个控制器和视图(asp.net页面)

现在我想知道如何在视图中显示自定义类的对象(例如,用户)的详细信息?我可以在ViewData collection中指定对象并在视图中渲染它吗?我已经有一个数据层(在ADO.NET中)正在为当前的ASP.NET web应用程序运行,所以我想使用它

我在我的控制器上试过这个

public ActionResult Index()
    {
        BusinessObject.User objUser = new BusinessObject.User();
        objUser.EmailId = "shyju@company.com";
        objUser.ProfileTitle = "Web developer with 6 yrs expereince";

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

        return View();
    }

如何在视图页面中使用此选项来显示用户详细信息?

您应该将对象作为视图模型(或视图模型的一部分,以及消息)传递给强类型视图。然后,您可以简单地在视图中引用模型属性

public class IndexViewModel
{
    public BusinessObject.User User { get; set; }
    public string Message { get; set; }
}
(或者,更好的是,只需要用户对象中您真正需要的属性)

控制器

public ActionResult Index()
{
    BusinessObject.User objUser = new BusinessObject.User();
    objUser.EmailId = "shyju@company.com";
    objUser.ProfileTitle = "Web developer with 6 yrs expereince";

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


this Inherits=“System.Web.MVC.ViewPage”是什么意思?@shyju-这意味着ViewPage的Model属性的类型为
MyWebSite.Models.IndexViewModel
——名称空间是假的,但意味着与示例中的Model类对应。
<%@ Page Title="" Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.MVC.ViewPage<MyWebSite.Models.IndexViewModel>" %>

<%= Html.Encode( Model.User.EmailId ) %>