我有一个自定义类MyCustomType。在那个类中,我有一个类型为bool的属性MyCustomProperty和另一个类型为bool的属性MyCustomProperty1。
我需要在我的视图中检查MyCustomProperty是否为true。我正在做以下事情:
<%if ( TempData[ViewDataConstants.MyCustomTypeKey] != null && ((MyCustomType)TempData[ViewDataConstants.MyCustomTypeKey]).MyCustomProperty %>show some custom content.
但出于某种原因,当我m running it I see error message that MyCustomTYpe could not be found are you missing an assembly reference bla-bla-bla. MyCustomType is in my controller it
公开并检查时,我甚至添加了对视图的引用。但它一直说没有MyCustomType类。我做错了什么?
有趣的是,出于某种原因,当我将它从Controllers命名空间移动到Common时,它突然起作用了。仍然不明白为什么它在Controllers命名空间中不起作用。 两个名称空间都明确包含在视图中。
答案 0 :(得分:1)
不知道为什么它不起作用,但老实说,在视图中使用所有这些代码对我来说是错误的。也许就像我一样,Visual Studio不喜欢在视图中编写C#代码:-)。
这应该是您的视图模型的属性:
public class MyViewModel
{
public bool MyCustomProperty { get; set; }
}
并在你的控制器内:
public ActionResult Foo()
{
var model = TempData[ViewDataConstants.MyCustomTypeKey] as MyCustomType ?? new MyCustomType();
var viewModel = Mapper.Map<MyCustomType, MyViewModel>(model);
return View(viewModel);
}
最后在你的观点中:
<% if (Model.MyCustomProperty) { %>
show some custom content.
<% } %>
现在你不再需要在视图中使用任何使用,铸件......了。