加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为ASP.NET MVC5关系创建DropDownList

发布时间:2020-12-15 04:03:33 所属栏目:百科 来源:网络整理
导读:这个问题在这里已经有一个答案: Populating a razor dropdownlist from a Listobject in MVC7个 我被困在ASP.NET MVC5中创建一个正确的创建/编辑视图.我有两个模型狗和人.一只狗属于一个人.我正在尝试在Dog的创建和编辑视图中创建一个下拉列表,这将允许我为
这个问题在这里已经有一个答案:> Populating a razor dropdownlist from a List<object> in MVC7个
我被困在ASP.NET MVC5中创建一个正确的创建/编辑视图.我有两个模型狗和人.一只狗属于一个人.我正在尝试在Dog的创建和编辑视图中创建一个下拉列表,这将允许我为该特定的狗选择一个Human的名字.这是我的型号:

人类:

public class Human
{
    public int ID { get; set; }
    public string Name { get; set; }
}

狗:

public class Dog
{
    public int ID { get; set; }
    public string Name { get; set; }
    public Human Human { get; set; }
}

我的创建动作:

// GET: /Dog/Create
public ActionResult Create()
{
    ViewBag.HumanSelection = db.Humen.Select(h => new SelectListItem
    {
        Value = h.ID.ToString(),Text = h.Name
    });
    return View();
}

这是我看法的相关部分:

<div class="form-group">
    @Html.LabelFor(model => model.Human.Name,new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.Human,ViewBag.HumanSelection);
    </div>
</div>

运行这个时我收到以下错误:

Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper<Test.Models.Dog>' has no applicable method named 'DropDownListFor' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

我是C#&实体框架.我究竟做错了什么?有没有手动查询数据库的方法?像Rails中的收集表单助手一样吗?
我遵循了一堆老式或太复杂的教程,让我无法遵循.

解决方法

要注意的是,如果您使用DropDownListFor(x => x.Human),则下拉列表的返回值应为人类对象.

不是在您自己的代码段中,将SelectListItem的值设置为Human的ID.因此,当您提交表单时,您将收到您选择的ID.

将以下内容添加到您的模型中:

public int HumanId { get; set; }

将您的下拉列表绑定到该int:

@Html.DropDownListFor(model => model.HumanId,(SelectList)ViewBag.HumanSelection);

现在,当你回到控制器时,使用该ID来查找你想要的实际人物:

[HttpPost]
public ActionResult Create (CreateModel model)
{
    if(model.HumanId > 0)
    {
        model.Human = GetHumanByID(model.HumanId);
        //or however you want to get the Human entoty from your database
    }
}

这是一个简化的解决方案,但我怀疑您的主要困惑来自于您希望从DropDownList接收到一个人,而实际上只返回一个int(ID).

编辑

我没有太多关于你的数据模型的信息,但是如果你使用实体框架,那么你的Dog类将会有一个叫做HumanId的外键属性.如果是这样,你甚至不需要像以前那样让人类实体得到.如果将所选的ID放在HumanId属性中,则实体框架应该能够使用它来创建所需的人/狗之间的关系.

如果是这种情况,似乎最好在你的问题上详细说明这一点,否则这将比实际确认更多的猜测.

编辑2在这里脱离

您的代码:

db.Humen

复数形式的男人是男人,女人是女人;但对于人类来说,这是人类:)虽然Humen听起来像一个令人敬畏的建议;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读