简体   繁体   English

asp.net MVC中的ViewData。*和TModel

[英]ViewData.* and TModel in asp.net MVC

After a week of asp.net mvc2, I still haven't understood the advantages of ViewData.model or rather how I can properly utilize Viewdata. 经过一周的asp.net mvc2,我仍然不了解ViewData.model的优势,或者如何正确利用Viewdata。 Can some teach me how to use Viewdata properly? 有人可以教我如何正确使用Viewdata吗?

Also what's TModel that's associated with viewdata? 还有与视图数据关联的TModel How does one utilize TModel ? 如何利用TModel The viewdata explanation in spark view engine talks about TModel and I couldn't get a clue of how I can use it in my projects. Spark视图引擎中viewdata解释讨论了TModel ,但我不知道如何在项目中使用它。 Can someone help me? 有人能帮我吗?

ViewData.Model is something that you can set in controller action and gets passed to the View where you can access it like this 您可以在控制器动作中设置ViewData.Model并将其传递给View,在其中您可以像这样访问它

<%=ViewData.Model.Description %>

or 要么

<%=Model.Description %>

that is, if the class that you are passing to the View contains property Description: 也就是说,如果要传递给View的类包含属性Description:

public ActionResult GetInstance(string id)
{
    MyContent content = GetContentFromDatastore(id);
    return View(content);
}

with this MyContent class 这个MyContent类

MyContent
{
    string id;
    string description;
}

Basically you are sending an instance of a class (an object with its properties set, most likely taken from the database) back to the View and display its data in the View, View being the ascx or aspx file, that eventually gets display to the user/visitor. 基本上,您是将类的实例(设置了属性的对象,很可能从数据库中获取)发送回View并在View中显示其数据,View是ascx或aspx文件,最终将其显示到用户/访客。 This is very simple example but it is unclear what exactly you want and how much you already know. 这是一个非常简单的示例,但是尚不清楚您到底想要什么以及已经知道多少。 But try to leave Spark (and other View Engines) out of the question for now until you know the ASP.NET MVC basics well. 但是,请暂时将Spark(和其他View Engine)排除在外,直到您对ASP.NET MVC的基本知识有所了解。

Mare is correct, you can use your models in your view by accessing the ViewData.ModelName.PropertyName item. Mare是正确的,您可以通过访问ViewData.ModelName.PropertyName项目在视图中使用模型。

Also while in your controller you can set certain key/value pairs in the ViewData dictionary: 同样,在控制器中时,您可以在ViewData字典中设置某些键/值对:

ViewData["Address1"] = "2222 Somewhere";

And then access it in your view: 然后在您的视图中访问它:

<%= Html.Encode(ViewData["Address1"]) %>

Obviously it wouldn't be ideal to use a key/value pair to handle all of your data, thats why you can create your own classes to encapsulate data, and pass THOSE to your view for easier manipulation. 显然,使用键/值对来处理所有数据并不是理想的选择,这就是为什么您可以创建自己的类来封装数据并将THOSE传递给视图以便于操作的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM