下拉列表[asp.net core 2.0]

时间:2018-07-12 08:29:12

标签: entity-framework asp.net-core-mvc asp.net-core-2.0

嗨,我的观点有误

如您所见,有一个输入和一个选择选项

<div class="form-group">
    <label asp-for="DomWasLoc" class="control-label"></label>
    <input asp-for="DomWasLoc" class="form-control" id="firstname" name="firstname" />
    <select class="form-control"
        id="name" name="name"
        asp-items="@(new SelectList(ViewBag.LocationList, "LocName","LocName"))">
        <option value="">- Select -</option>
    </select>
    <span asp-validation-for="DomWasLoc" class="text-danger"></span>
</div>

每次在下拉列表上选择一个项目时,就会在输入框中输入所选项目的值。

但是每次我单击“提交”时,我总是显示此错误

  

Create.cshtml中的AspNetCore._Views_DomesticWastes_Create_cshtml + d__25.MoveNext()   +               asp-items =“ @(new SelectList(ViewBag.LocationList,” LocName“,” LocName“))”>

我应该怎么做,以便在我单击“提交”时忽略选择内容,而仅从输入框中添加数据?

先谢谢大家! :)

1 个答案:

答案 0 :(得分:0)

对于相同的字段input,无需将selectDomWasLoc组合在一起。您可以将DomWasLoc直接绑定到select

演示代码如下:

            <div class="form-group">
            <label asp-for="DomWasLoc" class="control-label"></label>
            @*<input asp-for="DomWasLoc" class="form-control" />*@
            <select class="form-control"
                    asp-for="DomWasLoc"
                    asp-items="@(new SelectList(ViewBag.LocationList, "LocName","LocName"))">
                <option value="">- Select -</option>
            </select>
            <span asp-validation-for="DomWasLoc" class="text-danger"></span>
        </div>

更新:

完整代码:
1.型号

    public class Location
{
    public int Id { get; set; }
    public string LocName { get; set; }
}
public class DomesticWaste
{
    public int Id { get; set; }
    public string DomWasLoc { get; set; }
}
  1. 控制器

    // GET: DomesticWastes/Create
    public IActionResult Create()
    {
        List<Location> locationlist = new List<Location>() {
            new Location{ Id = 1,  LocName = "L1" },
            new Location{ Id = 2,LocName = "L2" },
            new Location{ Id = 3,LocName = "L3" }
        };
        ViewBag.LocationList = locationlist;
    
        return View();
    }
    
    // POST: DomesticWastes/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,DomWasLoc")] DomesticWaste domesticWaste)
    {
        if (ModelState.IsValid)
        {
            _context.Add(domesticWaste);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(domesticWaste);
    }