@ Html.DropDownListFor()即使选择了一个列表项,它始终显示空白 [英] @Html.DropDownListFor() Always Displays Blank even with a List Item selected

查看:126
本文介绍了@ Html.DropDownListFor()即使选择了一个列表项,它始终显示空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Pluralsight课程开展工作
https://app.pluralsight.com/library/courses/full-stack-dot-net-developer-fundamentals/table-of-contents



其中一部分是返回输入值并保存在数据库中的表单。 $ b

表单图片



无论在Html.DropDownListFor 被选中时,它显示为空白,提交表单将选定的值保存到数据库中,一旦选择了值,验证消息将停止显示,但下拉列表始终显示为空白。



感谢您的帮助。



Razor Code for Form:

  @model GigHub.Web.ViewModels.GigFormViewModel 
@ {
ViewBag.Title =Create;
Layout =〜/ Views / Shared / _Layout.cshtml;
}

< h2>添加Gig< / h2>
$ b $ @(Html.BeginForm(Create,Gigs))
{
@ Html.AntiForgeryToken()
< p class =alert alert-info>所有字段均为< strong>必需< / strong>< / p>
< div class =form-group>
@ Html.LabelFor(m => m.Venue)
@ Html.TextBoxFor(m => m.Venue,new {@class =form-control,autofocus =autofocus })
@ Html.ValidationMessageFor(m => m.Venue)
< / div>
< div class =form-group>
@ Html.LabelFor(m => m.Date)
@ Html.TextBoxFor(m => m.Date,new {@class =form-control,placeholder =eg: 2017年1月1日})
@ Html.ValidationMessageFor(m => m.Date)
< / div>
< div class =form-group>
@ Html.LabelFor(m => m.Time)
@ Html.TextBoxFor(m => m.Time,new {@class =form-control,placeholder =eg: 13:55})
@ Html.ValidationMessageFor(m => m.Time)
< / div>
< div class =form-group>
@ Html.LabelFor(m => m.Genre)
@ *新的SelectList(Model.Genres,Id,Name)&在新的{@class =form-control}用于默认选择之前,
应该是传递null叶子列表,传递空字符串会添加一个空白项目以供选择。 * @
@ Html.DropDownListFor(m => m.Genre,new SelectList(Model.Genres,Id,Name),--- Select One ---,new {@class =form-control})
@ Html.ValidationMessageFor(m => m.Genre)
< / div>
< button type =submitclass =btn btn-primary>储存< /按钮>
}
@section脚本
{
@ Scripts.Render(〜/ bundles / jqueryval)
}



使用GigHub.Web的控制器代码:

  。楷模; 
使用GigHub.Web.ViewModels;
使用Microsoft.AspNet.Identity;
使用System;
使用System.Linq;
使用System.Web.Mvc;

namespace GigHub.Web.Controllers
{
public class GigsController:Controller
{

private readonly ApplicationDbContext _context;

public GigsController()
{
_context = new ApplicationDbContext();

$ b [Authorize]
public ActionResult Create()
{
var viewModel = new GigFormViewModel
{
流派= _context.Genres.ToList()

};
return View(viewModel);

$ b [Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(GigFormViewModel viewModel)
{
if(!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
return View(Create,viewModel);

}



var gig = new Gig
{
ArtistId = User.Identity.GetUserId(),
DateTime = viewModel.GetDateTime(),
GenreId = viewModel.Genre,
Venue = viewModel.Venue
};

_context.Gigs.Add(gig);
_context.SaveChanges();


return RedirectToAction(Index,Home);



code
$ b

型号代码Genre.cs& amp ; Gig.cs:

 使用System.ComponentModel.DataAnnotations; 

namespace GigHub.Web.Models
{
public class Genre
{
public byte Id {get;组; }

[必需的]
[StringLength(255)]
public string Name {get;组; }
}
}

using System;
使用System.ComponentModel.DataAnnotations;

namespace GigHub.Web.Models
{
public class Gig
{
public int Id {get;组; }


public ApplicationUser Artist {get;组; }

[必需]


公共字符串ArtistId {get;组; }

public DateTime DateTime {get;组; }

[必需的]
[StringLength(255)]
public string Venue {get;组; }

[必需]
公共字节GenreId {get;组; }

public Genre Genre {get;组; }


$ b}
}

ViewModel的代码:

使用GigHub.Web.Models的

 ; 
使用System;
使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations;

namespace GigHub.Web.ViewModels
{
public class GigFormViewModel
{
[必需]
公共字符串Venue {get;组; }

[必需的]
[FutureDate]
public string Date {get;组; }

[必需]
[有效时间]
公共字符串时间{get;组; }

[必需]
公共字节类型{get;组; }


public IEnumerable< Genre>流派{get;组; }

$ b $ public DateTime GetDateTime()
{
return DateTime.Parse(string.Format({0} {1},Date,Time)) ;
}
}
}

CSS代码(也是bootstrap。 css:

  / * __________________________________________________________________________ * / 
body {
padding-top:50px;
padding-bottom:20px;
}

/ *设置填充以防止内容碰到边缘* /
.body-content {
padding-left: 15px;
padding-right:15px;
}

/ *覆盖默认的引导程序行为,其中水平描述列表
将截短太长而不适合的项左列
* /
.dl-horizo​​ntal dt {
white-space:normal;
}

/ *在窗体输入上设置宽度因为它们默认为100%宽* /
输入,
选择,
textarea {
最大宽度:280px;
}
/ * _____________________其他覆盖_____________________________________ * /
span.field-validation-error {
color:red;
font-weight:bold;
}

/ * _____________________ BootStrap覆盖_________________________________ * /

.navbar-inverse {
background-color:#f44;
border-color:#f44;
}

.navbar-inverse .navbar-nav> li>一个{
颜色:#fff;
}

.navbar-inverse .navbar-brand {
color:#fff;
}
.navbar-brand {
font-weight:700;
}
.navbar-inverse .navbar-nav> .open> a,.navbar-inverse .navbar-nav> .open> a:hover,.navbar-inverse .navbar-nav> .open> a:focus {
background-color:rgba(205,40,40,0.55);
}

.dropdown-menu {
-webkit-box-shadow:none;
box-shadow:none;

}
.navbar-inverse .navbar-nav> .dropdown> a .caret {
border-top-color:#fff;
border-bottom-color:#fff;
}

body {
font-size:17px;
}

正文,
h1,
h2,
h3,
h4,
h5,
h6 ,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family :Lato,Helvetica Neue,Helvetica,Arial,sans-serif;
}

.form-group {
margin-bottom:20px;
}
.form-control {
font-size:17px;
padding:20px 15px;
-ms-border-radius:9px;
border-radius:9px;
}
.form-control:focus {
border-color:#2196f3;
-webkit-box-shadow:none;
box-shadow:none;
}
.btn {
padding:7px 20px;
font-size:17px;
-ms-border-radius:9px;
border-radius:9px;
}


解决方案

解决方案找到:Site.css包含

  .form-control {
font-size:17px;
padding:20px 15px;
-ms-border-radius:9px;
border-radius:9px;
}

填充条目导致此问题。


I'm working through a Pluralsight course https://app.pluralsight.com/library/courses/full-stack-dot-net-developer-fundamentals/table-of-contents

Part of this is a form which returns entered values to be saved in the database.

Form Image

No matter which option in the "Html.DropDownListFor" is selected it shows as blank, submitting the form saves the selected value to the database fine, and once a value is chosen the validation message stops showing, but the dropdown is always showing as blank.

Thanks in advance for your help.

Razor Code for Form:

@model GigHub.Web.ViewModels.GigFormViewModel
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Add a Gig</h2>

@using (Html.BeginForm("Create", "Gigs"))
{
    @Html.AntiForgeryToken()
    <p class="alert alert-info">All fields are <strong>required</strong></p>
    <div class="form-group">
        @Html.LabelFor(m => m.Venue)
        @Html.TextBoxFor(m => m.Venue, new { @class = "form-control", autofocus = "autofocus" })
        @Html.ValidationMessageFor(m => m.Venue)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Date)
        @Html.TextBoxFor(m => m.Date, new { @class = "form-control", placeholder = "eg: 1 Jan 2017" })
        @Html.ValidationMessageFor(m => m.Date)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Time)
        @Html.TextBoxFor(m => m.Time, new { @class = "form-control", placeholder = "eg: 13:55" })
        @Html.ValidationMessageFor(m => m.Time)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @* Parameter after new SelectList(Model.Genres, "Id", "Name") & before new { @class = "form-control" } is for default choice,
            passing null leaves list as it should be, passing empty string adds a blank item to choose from.  *@
        @Html.DropDownListFor(m => m.Genre, new SelectList(Model.Genres, "Id", "Name"), "---Select One---", new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Genre)
    </div>
    <button type="submit" class="btn btn-primary">Save</button>
}
@section Scripts
{
    @Scripts.Render("~/bundles/jqueryval")
}

Code for Controller:

using GigHub.Web.Models;
using GigHub.Web.ViewModels;
using Microsoft.AspNet.Identity;
using System;
using System.Linq;
using System.Web.Mvc;

namespace GigHub.Web.Controllers
{
    public class GigsController : Controller
    {

        private readonly ApplicationDbContext _context;

        public GigsController()
        {
            _context = new ApplicationDbContext();
        }

        [Authorize]
        public ActionResult Create()
        {
            var viewModel = new GigFormViewModel
            {
                Genres = _context.Genres.ToList()           

             };           
            return View(viewModel);
        }

        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(GigFormViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                viewModel.Genres = _context.Genres.ToList();
                return View("Create", viewModel);

            }



            var gig = new Gig
            {
                ArtistId = User.Identity.GetUserId(),
                DateTime = viewModel.GetDateTime(),
                GenreId = viewModel.Genre,
                Venue = viewModel.Venue
            };

            _context.Gigs.Add(gig);
            _context.SaveChanges();


            return RedirectToAction("Index", "Home");
        }
    }
}

Model Code Genre.cs & Gig.cs:

using System.ComponentModel.DataAnnotations;

namespace GigHub.Web.Models
{
    public class Genre
    {
        public byte Id { get; set; }

        [Required]
        [StringLength(255)]
        public string Name { get; set; }
    }
}

using System;
using System.ComponentModel.DataAnnotations;

namespace GigHub.Web.Models
{
    public class Gig
    {
        public int Id { get; set; }


        public ApplicationUser Artist { get; set; }

        [Required]


 public string ArtistId { get; set; }

    public DateTime DateTime { get; set; }

    [Required]
    [StringLength(255)]
    public string Venue { get; set; }

    [Required]
    public byte GenreId { get; set; }

    public Genre Genre { get; set; }



}
}

Code for ViewModel:

using GigHub.Web.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace GigHub.Web.ViewModels
{
    public class GigFormViewModel
    {
        [Required]
        public string Venue { get; set; }

        [Required]
        [FutureDate]
        public string Date { get; set; }

        [Required]
        [ValidTime]
        public string Time { get; set; }

        [Required]
        public byte Genre { get; set; }


        public IEnumerable<Genre> Genres { get; set; }


        public DateTime GetDateTime()
        {
            return DateTime.Parse(string.Format("{0} {1}", Date, Time));
        }
    }
}

CSS Code(also bootstrap.css:

/*__________________________________________________________________________*/
body {
    padding-top: 50px;
    padding-bottom: 20px;
}

/* Set padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Override the default bootstrap behavior where horizontal description lists 
   will truncate terms that are too long to fit in the left column 
*/
.dl-horizontal dt {
    white-space: normal;
}

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}
/*_____________________Other Overrides_____________________________________*/
span.field-validation-error {
    color: red;
    font-weight: bold;
}

/*_____________________BootStrap Overrides_________________________________*/

.navbar-inverse {
    background-color: #f44;
    border-color: #f44;
}

.navbar-inverse .navbar-nav > li > a {
    color: #fff;
}

.navbar-inverse .navbar-brand {
    color: #fff;
}
.navbar-brand {
    font-weight: 700;
}
.navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .open > a:hover, .navbar-inverse .navbar-nav > .open > a:focus {
    background-color: rgba(205,40,40,0.55);
}

.dropdown-menu{
    -webkit-box-shadow:none;
    box-shadow:none;

}
.navbar-inverse .navbar-nav > .dropdown > a .caret {
    border-top-color: #fff;
    border-bottom-color: #fff;
}

body {
    font-size: 17px;
}

body,
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
    font-family: Lato, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.form-group {
    margin-bottom: 20px;
}
.form-control {
    font-size: 17px;
    padding: 20px 15px;
    -ms-border-radius: 9px;
    border-radius: 9px;
}
.form-control:focus {
    border-color: #2196f3;
    -webkit-box-shadow: none;
    box-shadow: none;
}
.btn {
    padding: 7px 20px;
    font-size: 17px;
    -ms-border-radius: 9px;
    border-radius: 9px;
}

解决方案

Solution found: Site.css contains

.form-control {
    font-size: 17px;
    padding: 20px 15px;
    -ms-border-radius: 9px;
    border-radius: 9px;
}

The padding entry is causing this issue.

这篇关于@ Html.DropDownListFor()即使选择了一个列表项,它始终显示空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆