Dropdownlist选择的值未保存到数据库中

时间:2017-04-18 08:12:29

标签: c# asp.net model-view-controller html.dropdownlistfor

我是新手。我正在使用Northwind数据库。 REGION DESCRIPTIONS出现在下拉列表中,但是当我尝试创建新客户时,没有新记录保存到数据库中,因为下拉列表选择的值不起作用。这两个表未与模型中的外键链接。 有什么帮助?!谢谢你。

this is the view :


    @model Northwind.Customer


@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>


@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Customer</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CustomerID, "", new { @class = "text-danger" })
            </div>
        </div>

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

        <div class="form-group">
            @Html.LabelFor(model => model.ContactName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

                @Html.EditorFor(model => model.ContactName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ContactName, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Region, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Region", String.Empty)
            </div>
        </div>

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Fax, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Fax, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Fax, "", new { @class = "text-danger" })
            </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>
}

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

这是控制器:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Northwind.Models;
using System.Data.Entity;
using System.Data.Entity.Validation;

namespace Northwind.Controllers
{
    public class CustomerController : Controller
    {
        dbNorthwindEntities db = new dbNorthwindEntities();





        // GET: Customer
        //  public ActionResult Index()
        //    {
        //   return View(db.Customers.ToList().Take(10));
        //    return View(db.Customers.ToList());
        //   }

        public ActionResult Index()
        {
            return View(db.Customers.ToList());
            //  var customers = db.Customers.Include(a => a.Region);
            //  return View(customers.ToList());
            //   var customers = db.Customers.Include(a => a.Region);

            //   return View(customers.ToList());
            // var customers = db.Customers.Include("Region");
            //return View(customers.ToList());
            //   return View(db.Customers.ToList());
        }



        //me marr formen per create
        [HttpGet]
        public ActionResult Create()
        {

            ViewBag.Region = new SelectList(db.Regions, "RegionDescription", "RegionDescription");
            return View();
        }



        //me bo post ne databaze
        [HttpPost]
        public ActionResult Create(Customer customer)
        {
            if (ModelState.IsValid)
            {
                db.Customers.Add(customer);
                try
                {

                    db.SaveChanges();
                }

                catch (DbEntityValidationException ex)
                {
                    foreach (var entityValidationErrors in ex.EntityValidationErrors)
                    {
                        foreach (var validationError in entityValidationErrors.ValidationErrors)
                        {
                            Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                        }
                    }
                }
                //return RedirectToAction("Index");
            }

            ViewBag.Region = new SelectList(db.Regions, "RegionDescription", "RegionDescription", customer.Region);
            return View(customer);
        }



        //me marr formen me get

        [HttpGet]
        public ActionResult Edit(string id)
        {
            dbNorthwindEntities db = new dbNorthwindEntities();

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

           Customer customer = db.Customers.Find(id);
            if (customer == null) { return HttpNotFound(); }
            ViewBag.Region = new SelectList(db.Regions, "RegionDescription", "RegionDescription", customer.Region);
            return View(customer);
        }


        //me postu

        [HttpPost]
        public ActionResult Edit([Bind(Include = "CustomerID,CompanyName,ContactName,Address,City,Region ,PostalCode, Country , Phone , Fax ")]Customer customer)
        {
            if (ModelState.IsValid)
            {



                db.Entry(customer).State = EntityState.Modified;

                db.SaveChanges();
                //  return  RedirectToAction("Index",  new {id = selectedc}) 
                return RedirectToAction("Index");
            }
            ViewBag.Region = new SelectList(db.Regions, "RegionDescription", "RegionDescription", customer.Region);
            return View(customer);

    }


    // GET: /Employee/Delete/5

    public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return HttpNotFound();
            }
            return View(customer);
        }


        /// POST: /Employee/Delete/5
        [HttpPost]
        public ActionResult Deletee(string id)
        {
            Customer customer = db.Customers.Find(id);
            db.Customers.Remove(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }






        [HttpGet]
        public ActionResult Details(string id)
        {
            dbNorthwindEntities db = new dbNorthwindEntities();
            Customer customer = db.Customers.Single(x => x.CustomerID == id);
            return View(customer);
        }

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

    }
}

这是客户和地区类:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Northwind
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    public partial class Customer
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Customer()
        {
            this.Orders = new HashSet<Order>();
            this.CustomerDemographics = new HashSet<CustomerDemographic>();
        }

        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
        public string City { get; set; }

        //     [StringLength(15, MinimumLength = 3, ErrorMessage = "Invalid")]
        //  [MaxLength(15), MinLength(5)]
        public virtual Region Regions { get; set; }

        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Order> Orders { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<CustomerDemographic> CustomerDemographics { get; set; }

    //    public string Region { get; set; }
      //  [NotMapped]
     //   public List<Region> RegionList { get; set; }

        //public Region Regionn { get; set; } // Navigation Property  

        //[NotMapped]
      //  public string RegionID { get; set; }

      //  [NotMapped]
      //     public List<Region> RegionList { get; set; }

     //   public int RegionID { get; set; }





    }
}




//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Northwind
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;

    public partial class Region
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Region()
        {
            this.Territories = new HashSet<Territory>();
        }

        public int RegionID { get; set; }
        public string RegionDescription { get; set; }

        public Nullable<int> SelectId { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Territory> Territories { get; set; }

       // public List<Customer> Customers { get; set; } // Navigation property  


    }
}

1 个答案:

答案 0 :(得分:0)

您可能应该为您的视图使用模型。 您可以添加Customer,Region列表和SelectedRegionId。然后使用这样的东西:  Html.DropDownListFor(model => model.SelectedRegionId, Model.Regions.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }))问题似乎是您没有变量来存储所选区域(在我的示例中为SelectedRegionId)。