首页 新闻 会员 周边 捐助

召唤守护使者们啦

0
悬赏园豆:30 [已解决问题] 解决于 2018-03-24 22:31

遇到一个问题,是性别方面,然后我注册的时候性别不显示   男or女,显示的是0-1,但是修改的时候会显示正常的下拉框选中性别,下面是代码,一下午了头都晕了

  1 using System.Collections.Generic;
  2 using System.Data.Entity;
  3 using System.Linq;
  4 using System.Net;
  5 using System.Web.Mvc;
  6 using MvcDemoTestThree._24.Models;
  7 using System;
  8 
  9 namespace MvcDemoTestThree._24.Controllers
 10 {
 11     [Authorize]
 12     public class StudentsController : Controller
 13     {
 14 
 15         private StudentDbContext db = new StudentDbContext();
 16 
 17         // GET: Students
 18         public ActionResult Index()
 19         {
 20             ViewBag.MajorList = GetMajorList();
 21             return View(db.Students.ToList());
 22         }
 23 
 24         // GET: Students/Details/5
 25         public ActionResult Details(int? id)
 26         {
 27             if (id == null)
 28             {
 29                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
 30             }
 31             Student student = db.Students.Find(id);
 32             if (student == null)
 33             {
 34                 return HttpNotFound();
 35             }
 36             return View(student);
 37         }
 38 
 39         // GET: Students/Create
 40         public ActionResult Create()
 41         {
 42             return View();
 43         }
 44 
 45         // POST: Students/Create
 46         // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 
 47         // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598
 48         [HttpPost]
 49         [ValidateAntiForgeryToken]      //用来阻止CSRF(跨站请求伪造)       Bind:用来阻止Over-Posting(过多提交攻击)。
 50         public ActionResult Create([Bind(Include = "ID,Name,Gender,Major,EntranceDate")] Student student)
 51         {
 52             if (ModelState.IsValid)
 53             {
 54                 db.Students.Add(student);
 55                 db.SaveChanges();
 56                 return RedirectToAction("Index");
 57             }
 58             ViewBag.GenderList = GetGenderList();
 59             return View(student);
 60         }
 61 
 62 
 63         // GET: Students/Edit/5
 64         public ActionResult Edit(int? id)
 65         {
 66             if (id == null)
 67             {
 68                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
 69             }
 70             Student student = db.Students.Find(id);
 71             if (student == null)
 72             {
 73                 return HttpNotFound();
 74             }
 75             ViewBag.GenderList = GetGenderList();
 76             return View(student);
 77         }
 78 
 79         private List<SelectListItem> GetGenderList()
 80         {
 81             return new List<SelectListItem>() {
 82               new SelectListItem()
 83               {
 84                      Text = "",
 85                      Value = "1"
 86               },
 87               new SelectListItem()
 88               {
 89                      Text = "",
 90                      Value = "0"
 91               }
 92             };
 93         }
 94 
 95         // POST: Students/Edit/5
 96         // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 
 97         // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598
 98         [HttpPost]
 99         [ValidateAntiForgeryToken]
100         public ActionResult Edit([Bind(Include = "ID,Name,Gender,Major,EntranceDate")] Student student)
101         {
102             if (ModelState.IsValid)
103             {
104                 db.Entry(student).State = EntityState.Modified;
105                 db.SaveChanges();
106                 return RedirectToAction("Index");
107             }
108             ViewBag.GenderList = GetGenderList();
109             return View(student);
110         }
111 
112         // GET: Students/Delete/5
113         public ActionResult Delete(int? id)
114         {
115             if (id == null)
116             {
117                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
118             }
119             Student student = db.Students.Find(id);
120             if (student == null)
121             {
122                 return HttpNotFound();
123             }
124             return View(student);
125         }
126 
127         // POST: Students/Delete/5
128         [HttpPost, ActionName("Delete")]
129         [ValidateAntiForgeryToken]
130         public ActionResult DeleteConfirmed(int id)
131         {
132             Student student = db.Students.Find(id);
133             db.Students.Remove(student);
134             db.SaveChanges();
135             return RedirectToAction("Index");
136         }
137 
138         protected override void Dispose(bool disposing)
139         {
140             if (disposing)
141             {
142                 db.Dispose();
143             }
144             base.Dispose(disposing);
145         }
146 
147         #region GetMajorList
148         private List<SelectListItem> GetMajorList()
149         {
150             var majors = db.Students.OrderBy(m => m.Major).Select(m => m.Major).Distinct();
151 
152             var items = new List<SelectListItem>();
153             foreach (string major in majors)
154             {
155                 items.Add(new SelectListItem
156                 {
157                     Text = major,
158                     Value = major
159                 });
160             }
161             return items;
162         }
163         #endregion
164 
165 
166         #region 根据条件模糊查询Index
167         [HttpPost]
168         [ValidateAntiForgeryToken]
169         public ActionResult Index(string Major, string Name)
170         {
171             var students = db.Students as IQueryable<Student>;
172             if (!String.IsNullOrEmpty(Name))
173             {
174                 students = students.Where(m => m.Name.Contains(Name));
175             }
176 
177             if (!String.IsNullOrEmpty(Major))
178             {
179                 students = students.Where(m => m.Major == Major);
180             }
181 
182             ViewBag.MajorList = GetMajorList();
183             return View(students.ToList());
184         }
185         #endregion
186         
187     }
188 }
这里是stu的控制器,GetGenderList是显示男女
 1 @model MvcDemoTestThree._24.Models.Student
 2 
 3 @{
 4     ViewBag.Title = "Edit";
 5 }
 6 
 7 <h2>Edit</h2>
 8 
 9 
10 @using (Html.BeginForm())
11 {
12     @Html.AntiForgeryToken()
13     
14     <div class="form-horizontal">
15         <h4>Student</h4>
16         <hr />
17         @Html.ValidationSummary(true, "", new { @class = "text-danger" })
18         @Html.HiddenFor(model => model.ID)
19 
20         <div class="form-group">
21             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
22             <div class="col-md-10">
23                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
24                 @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
25             </div>
26         </div>
27 
28         <div class="form-group">
29             @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
30             <div class="col-md-10">
31                 @Html.DropDownListFor(model => model.Gender,ViewBag.GenderList as IEnumerable<SelectListItem>, new { @class = "form-control" })
32                 @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
33             </div>
34         </div>
35 
36         <div class="form-group">
37             @Html.LabelFor(model => model.Major, htmlAttributes: new { @class = "control-label col-md-2" })
38             <div class="col-md-10">
39                 @Html.EditorFor(model => model.Major, new { htmlAttributes = new { @class = "form-control" } })
40                 @Html.ValidationMessageFor(model => model.Major, "", new { @class = "text-danger" })
41             </div>
42         </div>
43 
44         <div class="form-group">
45             @Html.LabelFor(model => model.EntranceDate, htmlAttributes: new { @class = "control-label col-md-2" })
46             <div class="col-md-10">
47                 @Html.EditorFor(model => model.EntranceDate, new { htmlAttributes = new { @class = "form-control" } })
48                 @Html.ValidationMessageFor(model => model.EntranceDate, "", new { @class = "text-danger" })
49             </div>
50         </div>
51 
52         <div class="form-group">
53             <div class="col-md-offset-2 col-md-10">
54                 <input type="submit" value="Save" class="btn btn-default" />
55             </div>
56         </div>
57     </div>
58 }
59 
60 <div>
61     @Html.ActionLink("Back to List", "Index")
62 </div>
63 
64 @section Scripts {
65     @Scripts.Render("~/bundles/jqueryval")
66 }
这是修改页面,性别显示正常
 1 @model MvcDemoTestThree._24.Models.Student
 2 
 3 @{
 4     ViewBag.Title = "Create";
 5 }
 6 
 7 <h2>Create</h2>
 8 
 9 
10 @using (Html.BeginForm()) 
11 {
12     @Html.AntiForgeryToken()
13     
14     <div class="form-horizontal">
15         <h4>Student</h4>
16         <hr />
17         @Html.ValidationSummary(true, "", new { @class = "text-danger" })
18         <div class="form-group">
19             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
20             <div class="col-md-10">
21                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
22                 @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
23             </div>
24         </div>
25 
26         <div class="form-group">
27             @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
28             <div class="col-md-10">
29                 @Html.DropDownListFor(model => model.Gender, ViewBag.GenderList as IEnumerable<SelectListItem>, new { @class = "form-control" })
30                 @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
31              </div>
32         </div>
33 
34         <div class="form-group">
35             @Html.LabelFor(model => model.Major, htmlAttributes: new { @class = "control-label col-md-2" })
36             <div class="col-md-10">
37                 @Html.EditorFor(model => model.Major, new { htmlAttributes = new { @class = "form-control" } })
38                 @Html.ValidationMessageFor(model => model.Major, "", new { @class = "text-danger" })
39             </div>
40         </div>
41 
42         <div class="form-group">
43             @Html.LabelFor(model => model.EntranceDate, htmlAttributes: new { @class = "control-label col-md-2" })
44             <div class="col-md-10">
45                 @Html.EditorFor(model => model.EntranceDate, new { htmlAttributes = new { @class = "form-control" } })
46                 @Html.ValidationMessageFor(model => model.EntranceDate, "", new { @class = "text-danger" })
47             </div>
48         </div>
49 
50         <div class="form-group">
51             <div class="col-md-offset-2 col-md-10">
52                 <input type="submit" value="Create" class="btn btn-default" />
53             </div>
54         </div>
55     </div>
56 }
57 
58 <div>
59     @Html.ActionLink("Back to List", "Index")
60 </div>
61 
62 @section Scripts {
63     @Scripts.Render("~/bundles/jqueryval")
64 }
这是注册create,就是这里出问题,要么显示数字要么报错
@Html.DropDownListFor(model => model.Gender, ViewBag.GenderList as IEnumerable<SelectListItem>, new { @class = "form-control" })

“/”应用程序中的服务器错误。


 

不存在具有键“Gender”的“IEnumerable<SelectListItem>”类型的 ViewData 项。

说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 

异常详细信息: System.InvalidOperationException: 不存在具有键“Gender”的“IEnumerable<SelectListItem>”类型的 ViewData 项。

源错误: 

行 27:             @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
行 28:             <div class="col-md-10">
行 29:                 @Html.DropDownListFor(model => model.Gender, ViewBag.GenderList as IEnumerable<SelectListItem>, new { @class = "form-control" })
行 30:                 @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
行 31:              </div>


源文件: d:\C#基础练习\MVC4_3_15\MvcApplication1\MvcDemoTestThree.24\Views\Students\Create.cshtml    行: 29 

堆栈跟踪: 

[InvalidOperationException: 不存在具有键“Gender”的“IEnumerable<SelectListItem>”类型的 ViewData 项。]
   System.Web.Mvc.Html.SelectExtensions.GetSelectData(HtmlHelper htmlHelper, String name) +265
   System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper, ModelMetadata metadata, String optionLabel, String name, IEnumerable`1 selectList, Boolean allowMultiple, IDictionary`2 htmlAttributes) +255
   System.Web.Mvc.Html.SelectExtensions.DropDownListHelper(HtmlHelper htmlHelper, ModelMetadata metadata, String expression, IEnumerable`1 selectList, String optionLabel, IDictionary`2 htmlAttributes) +56
   System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList, String optionLabel, IDictionary`2 htmlAttributes) +234
   System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList, Object htmlAttributes) +141
   ASP._Page_Views_Students_Create_cshtml.Execute() in d:\C#基础练习\MVC4_3_15\MvcApplication1\MvcDemoTestThree.24\Views\Students\Create.cshtml:29
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +270
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +121
   System.Web.WebPages.StartPage.RunPage() +63
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +100
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9744373
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

这是错误信息,真的弄的头晕了

问题补充:
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.ComponentModel.DataAnnotations;
 5 using System.Data.Entity;
 6 using System.Linq;
 7 using System.Web;
 8 
 9 namespace MvcDemoTestThree._24.Models
10 {
11     public class Student
12     {
13 
14         /// <summary>
15         /// 创建五个属性
16         /// </summary>
17 
18         public int ID { get; set; }
19         [Required]
20         [DisplayName("姓名")]
21         [StringLength(200,MinimumLength=2)]
22         public string Name { get; set; }
23         [DisplayName("性别")]
24         [Required]
25         [Range(0,1)]
26         public int Gender { get; set; }
27         [Required]
28         [DisplayName("专业")]
29         [StringLength(200)]
30         public string Major { get; set; }
31         [DisplayName("出生日期")]
32         [DataType(DataType.Date)]
33         [DisplayFormat(DataFormatString = ("{0:yyyy-MM-dd}"),ApplyFormatInEditMode=true)]
34         public DateTime EntranceDate { get; set; }
35     }
36     
37 
38     /// <summary>
39     /// 创建数据库
40     /// </summary>
41 
42     public class StudentDbContext:DbContext
43     {
44         public DbSet<Student> Students { get; set; }
45     }
46 
47 }
model
cocoyoona的主页 cocoyoona | 初学一级 | 园豆:20
提问于:2018-03-24 16:42

model.Gender的类型是如何定义的?

dudu 6年前

@dudu: [DisplayName("性别")][Required]
[Range(0,1)]
public int Gender { get; set; }

猪zzZ 6年前
< >
分享
最佳答案
0

参考 Create DropDownList using HtmlHelper

public class Student
{
    public int StudentId { get; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; }
    public Gender StudentGender { get; set; }
}

public enum Gender
{
    Male,
    Female    
}
@model Student
@Html.DropDownList("StudentGender", 
                    new SelectList(Enum.GetValues(typeof(Gender))),
                    "Select Gender",
                    new { @class = "form-control" })
收获园豆:30
dudu | 高人七级 |园豆:30778 | 2018-03-24 17:26
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册