gpt4 book ai didi

c# - 找不到 C# MVC 模型属性的定义

转载 作者:太空宇宙 更新时间:2023-11-03 23:16:21 32 4
gpt4 key购买 nike

我有这个模型:

public class RamalModel
{
public int ID { get; set; }
public string Nome { get; set; }
public int Numero { get; set; }
}

然后我创建了一个局部 View :

@model RamalAguia.Models.RamalModel

<div>

<h4>@Model.Nome</h4>

<span>@Model.Numero</span>
<hr />

</div>

在我的 Controller 中,我正在使用它:

public class HomeController : Controller
{
RamaDb _db = new RamaDb();

public ActionResult Index()
{
var model = _db.Ramais.ToList();

return View(model.ToList());
}
}

但是当我尝试放置时:

@Html.RenderPartial("_Ramal", Model.Nome , new ViewDataDictionary());

它不起作用并显示此错误:

Error 1 'System.Collections.Generic.List' does not contain a definition for 'Nome' and no extension method 'Nome' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?) c:\dev\Teste\RamalAguia\RamalAguia\Views\Home\Index.cshtml 9 37 RamalAguia

有人可以帮助我吗?谢谢

最佳答案

您的型号是 List<RamaModel>而你在

@Html.RenderPartial("_Ramal", Model.Nome , new ViewDataDictionary());

试图从变量类型中获取 RamaModel不是来自列表。

要渲染第一个元素,您可以使用:

@Html.RenderPartial("_Ramal", Model[0].Nome , new ViewDataDictionary());

或者显示列表中的所有 ramas:

@foreach (var item in Model)
{
@Html.RenderPartial("_Ramal", item.Nome , new ViewDataDictionary());
}

编辑

在 View 中

改变

@model RamalAguia.Models.RamalModel

@model List<RamalAguia.Models.RamalModel>

在 Controller 中

return View(model.ToList());

.ToList()是不必要的。

关于c# - 找不到 C# MVC 模型属性的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37169809/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com