如何在 MVC C# 的下拉列表中显示同一张表中的两个字段?

huangapple go评论65阅读模式
英文:

How to display 2 fields from the same table in the drop-down list MVC C#

问题

我是C#的初学者,遇到了问题。
我有一个"Person"表格,包含(id、名字、姓氏)。我想要创建一个新的人,但是我只有下拉列表中的名字。我需要显示名字和姓氏。

我的控制器:

// GET: Magazyn
public ActionResult Index()
{
    var magazyn = db.Magazyn.Include(m => m.Tools).Include(m => m.Person);
    return View(magazyn.ToList());
}

// GET: Magazyn/Details/5
public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Magazyn magazyn = db.Magazyn.Find(id);
    if (magazyn == null)
    {
        return HttpNotFound();
    }
    return View(magazyn);
}

// GET: Magazyn/Create
public ActionResult Create()
{
    ViewBag.IdOsoby = new SelectList(db.Person, "Id", "Name", "Last Name");
    return View();
}

视图:

<div class="form-group">
    @Html.LabelFor(model => model.IdPerson, "IdPerson", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("IdPerson", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.IdPerson, "", new { @class = "text-danger" })
    </div>
</div>

如果需要进一步的帮助,请随时告诉我。

英文:

I'm beginner in c#, and I have problem.
I have a "Person" table, (id, first name, last name). I want to create a new person, but I only have the name in the drop-down list. I need to display the name and last name.

My controller:

// GET: Magazyn
    public ActionResult Index()
    {
        var magazyn = db.Magazyn.Include(m =&gt; m.Tools).Include(m =&gt; m.Person);
        return View(magazyn.ToList());
    }

    // GET: Magazyn/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Magazyn magazyn = db.Magazyn.Find(id);
        if (magazyn == null)
        {
            return HttpNotFound();
        }
        return View(magazyn);
    }

    // GET: Magazyn/Create
    public ActionResult Create()
    {
      
        ViewBag.IdOsoby = new SelectList(db.Person, &quot;Id&quot;, &quot;Name&quot;,  &quot;Last Name&quot;);
        return View();
    }

View:

&lt;div class=&quot;form-group&quot;&gt;
        @Html.LabelFor(model =&gt; model.IdPerson, &quot;IdPerson&quot;, htmlAttributes: new { @class = &quot;control-label col-md-2&quot; })
        &lt;div class=&quot;col-md-10&quot;&gt;
            @Html.DropDownList(&quot;IdPerson&quot;, null, htmlAttributes: new { @class = &quot;form-control&quot; })
            @Html.ValidationMessageFor(model =&gt; model.IdPerson, &quot;&quot;, new { @class = &quot;text-danger&quot; })
        &lt;/div&gt;
    &lt;/div&gt;

答案1

得分: 1

以下是翻译好的部分:

你可以这样做:

public ActionResult Create()
{
   var selectList = db.Person.Select(x => new SelectListItem { Text = $"{x.Firstname} - {x.Lastname}", Value = x.Id.ToString() });
   ViewBag.IdOsoby = new SelectList(selectList, "Value", "Text");

   return View();
}

错误发生是因为我们尝试格式化名字和姓氏的字符串。有几种方法可以解决这个问题。首先,继续创建另一个 `Person` 类,确保将其标记为 `partial` 并确保它与您的 `Person` 实体在同一个命名空间中。类似于以下内容:

public partial class Person
{
    public string FullName => $"{Firstname} {Lastname}";
}

如您所见,我引入了一个只读属性 `FullName`,它是名字和姓氏的组合。现在,您可以在 `Create` 操作中更改代码如下:

public ActionResult Create()
{
   ViewBag.IdOsoby = new SelectList(db.Person.ToList(), "Id", "FullName");

   return View();
}
英文:

You can do something like:

public ActionResult Create()
{
   var selectList = db.Person.Select(x =&gt; new SelectListItem { Text = $&quot;{x.Firstname} - {x.Lastname}&quot;, Value = x.Id.ToString()});
   ViewBag.IdOsoby = new SelectList(selectList, &quot;Value&quot;, &quot;Text&quot;);

   return View();
}

The error happens because we're trying to format the string of first name and surname. There's a couple of ways to do this. Firstly go ahead and make another Person class, make sure to mark it partial and ensure it is in the same namespace as your Person entity. So something like:

public partial class Person
{
    public string FullName =&gt; $&quot;{Firstname} {Lastname}&quot;;
}

As you can see I have introduced a readonly property of fullname which is a combination of First and Last name. Now you can change your code in the Create action as:

public ActionResult Create()
{
   ViewBag.IdOsoby = new SelectList(db.Person.ToList(), &quot;Id&quot;, &quot;FullName&quot;);

   return View();
}

答案2

得分: 0

以下是您的代码的翻译部分:

我犯了一些简单而难以理解的错误。我的代码目前看起来像这样。下拉列表仍然不起作用。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Legoland.Models;

namespace Legoland.Controllers
{
    public class MagazynController : Controller
    {
        private LegolandEntities db = new LegolandEntities();

        // GET: Magazyn
        public ActionResult Index()
        {
            var magazyn = db.Magazyn.Include(m => m.xxx).Include(m => m.Person);
            return View(magazyn.ToList());
        }

        // GET: Magazyn/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Magazyn magazyn = db.Magazyn.Find(id);
            if (magazyn == null)
            {
                return HttpNotFound();
            }
            return View(magazyn);
        }

        // GET: Magazyn/Create
        public ActionResult Create()
        {
            ViewBag.Idxxx = new SelectList(db.xxx, "Id", "xxx");
            ViewBag.IdPerson = new SelectList(db.Person, "Id", "Name", "LastName");
            return View();
        }

        // POST: Magazyn/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,IdPerson,Idxxx,yyy,zzzz")] Magazyn magazyn)
        {
            if (ModelState.IsValid)
            {
                db.Magazyn.Add(magazyn);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.Idxxx = new SelectList(db.xxx, "Id", "xxx", magazyn.Idxxx);
            ViewBag.IdPerson = new SelectList(db.Person, "Id", "Name", "LastName", magazyn.Person);
            return View(magazyn);
        }

        // GET: Magazyn/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Magazyn magazyn = db.Magazyn.Find(id);
            if (magazyn == null)
            {
                return HttpNotFound();
            }
            ViewBag.Idxxx = new SelectList(db.xxx, "Id", "xxx", magazyn.Idxxx);
            var selectList = db.Person.Select(x => new SelectListItem { Text = $"{x.Name} - {x.LastName}", Value = x.Id.ToString() });
            ViewBag.IdPerson = new SelectList(selectList, "Value", "Text");
            return View(magazyn);
        }

        // POST: Magazyn/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,IdPerson,Idxxx,yyy,zzz")] Magazyn magazyn)
        {
            if (ModelState.IsValid)
            {
                db.Entry(magazyn).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.Idxxx = new SelectList(db.xxx, "Id", "yyy", magazyn.Idxxx);
            var selectList = db.Person.Select(x => new SelectListItem { Text = $"{x.Name} - {x.LastName}", Value = x.Id.ToString() });
            ViewBag.IdPerson = new SelectList(selectList, "Value", "Text");
            return View(magazyn);
        }

        // GET: Magazyn/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Magazyn magazyn = db.Magazyn.Find(id);
            if (magazyn == null)
            {
                return HttpNotFound();
            }
            return View(magazyn);
        }

        // POST: Magazyn/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Magazyn magazyn = db.Magazyn.Find(id);
            db.Magazyn.Remove(magazyn);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

视图 Create.cs 的翻译如下:

@model Legoland.Models.Magazyn

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Magazyn</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.Person, "IdPerson", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("IdPerson", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.IdPerson, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

希望这些翻译对您有所帮助。如果您需要进一步的帮助,请随时提问。

英文:

I make some simple, incomprehensible mistakes. My code currently looks like this. The drop-down list still does not work.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Legoland.Models;
namespace Legoland.Controllers
{
public class MagazynController : Controller
{
private LegolandEntities db = new LegolandEntities();
// GET: Magazyn
public ActionResult Index()
{
var magazyn = db.Magazyn.Include(m =&gt; m.xxx).Include(m =&gt; m.Person);
return View(magazyn.ToList());
}
// GET: Magazyn/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Magazyn magazyn = db.Magazyn.Find(id);
if (magazyn == null)
{
return HttpNotFound();
}
return View(magazyn);
}
// GET: Magazyn/Create
public ActionResult Create()
{
ViewBag.Idxxx = new SelectList(db.xxx, &quot;Id&quot;, &quot;xxx&quot;);
ViewBag.IdPerson = new SelectList(db.Person, &quot;Id&quot;, &quot;Name&quot;, &quot;LastName&quot;);
return View();
}
// POST: Magazyn/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = &quot;Id,IdPerson,Idxxx,yyy,zzzz&quot;)] Magazyn magazyn)
{
if (ModelState.IsValid)
{
db.Magazyn.Add(magazyn);
db.SaveChanges();
return RedirectToAction(&quot;Index&quot;);
}
ViewBag.Idxxx = new SelectList(db.xxx, &quot;Id&quot;, &quot;xxx&quot;, magazyn.Idxxx);
ViewBag.IdPerson = new SelectList(db.Person, &quot;Id&quot;, &quot;Name&quot;, &quot;LastName&quot;, magazyn.Person);
return View(magazyn);
}
// GET: Magazyn/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Magazyn magazyn = db.Magazyn.Find(id);
if (magazyn == null)
{
return HttpNotFound();
}
ViewBag.Idxxx = new SelectList(db.xxx, &quot;Id&quot;, &quot;xxx&quot;, magazyn.Idxxx);
var selectList = db.Person.Select(x =&gt; new SelectListItem { Text = $&quot;{x.Name} - {x.LastName}&quot;, Value = x.Id.ToString() });
ViewBag.IdPerson = new SelectList(selectList, &quot;Value&quot;, &quot;Text&quot;);
return View(magazyn);
}
// POST: Magazyn/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = &quot;Id,IdPerson,Idxxx,yyy,zzz&quot;)] Magazyn magazyn)
{
if (ModelState.IsValid)
{
db.Entry(magazyn).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction(&quot;Index&quot;);
}
ViewBag.Idxxx = new SelectList(db.xxx, &quot;Id&quot;, &quot;yyy&quot;, magazyn.Idxxx);
var selectList = db.Person.Select(x =&gt; new SelectListItem { Text = $&quot;{x.Name} - {x.LastName}&quot;, Value = x.Id.ToString() });
ViewBag.IdPerson = new SelectList(selectList, &quot;Value&quot;, &quot;Text&quot;);
return View(magazyn);
}
// GET: Magazyn/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Magazyn magazyn = db.Magazyn.Find(id);
if (magazyn == null)
{
return HttpNotFound();
}
return View(magazyn);
}
// POST: Magazyn/Delete/5
[HttpPost, ActionName(&quot;Delete&quot;)]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Magazyn magazyn = db.Magazyn.Find(id);
db.Magazyn.Remove(magazyn);
db.SaveChanges();
return RedirectToAction(&quot;Index&quot;);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}

And View Create.cs:

@model Legoland.Models.Magazyn
@{
ViewBag.Title = &quot;Create&quot;;
}
&lt;h2&gt;Create&lt;/h2&gt;
@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()
&lt;div class=&quot;form-horizontal&quot;&gt;
&lt;h4&gt;Magazyn&lt;/h4&gt;
&lt;hr /&gt;
@Html.ValidationSummary(true, &quot;&quot;, new { @class = &quot;text-danger&quot; })
&lt;div class=&quot;form-group&quot;&gt;
@Html.LabelFor(model =&gt; model.Person, &quot;IdPerson&quot;, htmlAttributes: new { @class = &quot;control-label col-md-2&quot; })
&lt;div class=&quot;col-md-10&quot;&gt;
@Html.DropDownList(&quot;IdPerson&quot;, null, htmlAttributes: new { @class = &quot;form-control&quot; })
@Html.ValidationMessageFor(model =&gt; model.IdPerson, &quot;&quot;, new { @class = &quot;text-danger&quot; })
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;div class=&quot;col-md-offset-2 col-md-10&quot;&gt;
&lt;input type=&quot;submit&quot; value=&quot;Create&quot; class=&quot;btn btn-default&quot; /&gt;
&lt;/div&gt;
&lt;/div&gt;
}
&lt;div&gt;
@Html.ActionLink(&quot;Back to List&quot;, &quot;Index&quot;)
&lt;/div&gt;

huangapple
  • 本文由 发表于 2020年1月3日 17:53:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定