【问题标题】:passing variables / models in mvc 4 c#在 mvc 4 c# 中传递变量/模型
【发布时间】:2013-06-28 17:55:46
【问题描述】:

好的,我有 2 个模型

模型客户

[Table("Clients")]
public class Clients
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

    public int ClientID { get; set; }

    public string Client { get; set; }
    public string Address { get; set; }
    public string State { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public int Zip { get; set; }
    public string Phone { get; set; }
    public string LogoLocation { get; set; }
    public string ContactName { get; set; }
    public string ContactPhone { get; set; }
    public string ContactEmail { get; set; }
    public int Authorized { get; set; }

    public string Note { get; set; }
    public string Comment { get; set; }

    public virtual ICollection<Countys> Countys { get; set; }

}

示范县

[Table("Countys")]
public class Countys
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

    public int CountyID { get; set; }
    public int ClientID { get; set; }

    public string County { get; set; }
    public string Note { get; set; }
    public string Comment { get; set; }

    public virtual ICollection<TownShips> Townships { get; set; }

}

** 此时我的县索引控制器**

     public ActionResult Index(int id)
    {
        var cnty = from r in db.Clients
                   where r.ClientID == id
                   select r;

        if (cnty != null)
        {
            try
            {
                return View(cnty);
            }
            catch (Exception ex)
            {

            }
        }
        return HttpNotFound();

     }

我的视图是标准生成的视图:

@model OilNGasWeb.ModelData.Clients

@{
ViewBag.Title = "Index"; 
}

<h2>County's for </h2> 

<p>
@Html.ActionLink("Create New", "Create",new { id = Model.ClientID },null)
</p>


<table>
<tr>

    <th>
        @Html.DisplayNameFor(model => model.Countys.First().County) 
    </th>

    <th>
        @Html.DisplayNameFor(model => model.Countys.First().Note) 
    </th>

    <th>
        @Html.DisplayNameFor(model => model.Countys.First().Comment) 
    </th>

</tr>
</Table>

例外:

System.InvalidOperationException:传入字典的模型项的类型为 System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary字典)在 System.Web.Mvc.WebViewPage1.SetViewData(ViewDataDictionary viewData) at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.&lt;&gt;c__DisplayClass1a. &lt;InvokeActionResultWithFilters&gt;b__17() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 继续)在 System.Web.Mvc.ControllerActionInvoker。 c_DisplayClass1a.c_DisplayClass1c.b_19() 在 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) 在 System.Web .Mvc.Async.AsyncControllerActionInvoker.c_DisplayClass25.c_DisplayClass2a。 b_20() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.c_DisplayClass25。 b_22(IAsyncResult asyncResult);

【问题讨论】:

  • 这听起来很多就像以前的问题,已经有一些答案:how to pass one-to-many from controller to view in mvc4
  • 是的,但它们都不是我的解决方案,我也将它们标记为删除,因为重复被告知恢复它们并更改问题中的所有代码是不可接受的。

标签: c# asp.net-mvc-4 model controller views


【解决方案1】:

如果您的视图需要Clients 对象(其中包括Countys 对象的枚举),那么您需要将Clients 对象传递给您的视图:

public ActionResult Index(int id)
{
    var client = (from r in Clients
                 where r.ClientID == id
                 select r).SingleOrDefault();

    if (client != null)
    {
        return View(client);
    }
    return HttpNotFound();

 }

在视图中,您将声明一个 Clients 模型:

@model OilNGasWeb.ModelData.Clients

然后在视图中,您将可以访问有关Clients 对象的信息以及它包含的Countys 对象的(可能为空)列表。本质上,您的代码“错误”是视图在逻辑上位于 Clients 的上下文中(真的很难不只说“客户端”,您可能想要处理类名),但您给它的只是Countys 对象的枚举。

注意:为了更安全的代码,您可能希望将该枚举初始化为其应为的值,以防万一它是空列表时未填充它。您可以在类的构造函数中执行此操作。例如,如果您想将其初始化为 List&lt;Countys&gt;,那么构造函数可能是这样的:

public Clients()
{
    Countys = new List<Countys>();
}

这样属性永远不会是null,最坏的情况是它是一个空列表,在视图中更容易管理。

【讨论】:

  • 太棒了,您能否给我一些有关如何获取数据的示例语法...我已经习惯了 vb.net 并且一直在尝试使用 @Html.DisplayFor(modelItem => item. Clients.Countys.CountyName(或 w/e 字段)
  • @Pakk:尝试类似:@Html.DisplayFor(modelItem =&gt; item.Clients.Countys.First().CountyName) 这有点不直观,因为人们会期望 .First() 在空列表上抛出异常。但在这种情况下,HTML 帮助器方法实际上并没有执行该行。它只是通过反射遵循引用的类型。因此,即使在空列表上.First() 也应该在这种情况下工作。 (尽管根据您的代码,我不确定此示例中 item 是什么类型。我希望类似 Model.Countys.First().CountyName 但我不能确定。)
  • 好的,我改变了我的代码,你能告诉我为什么它不工作吗?或者这是一个不同的问题
  • @Pakk:为什么您的模型是ClientsIEnumerable? (注意:我的回答有误,模型应该是Clients 对象而不是Countys 对象。我现在已经更正了。)您只使用了一个Clients 对象,对吧?
  • 是的,我现在只使用 Clients 对象(删除了 Ienumerable),如果它不是 Ienumerable,我也会进入视图,如果它没有出错,看到错误 try / catch 和或踏入它似乎不起作用。给我几个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-19
  • 1970-01-01
  • 2014-03-16
  • 2017-04-20
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
相关资源
最近更新 更多