简体   繁体   English

如何将下拉值从视图发送到控制器

[英]How to send dropdown value from view to controller

I have the following create view 我有以下创建视图

   @model Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad

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

<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-4">
        <h2>Create</h2>
        <ol class="breadcrumb">
            <li>
                @Html.ActionLink("List", "Index")
            </li>
            <li class="active">
                <strong>Create</strong>
            </li>
        </ol>
    </div>
    <div class="col-sm-8">
        <div class="title-action">
            @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-primary"})
        </div>
    </div>
</div>


<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>Create Propiedad</h5>
                </div>
                <div class="ibox-content">

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

    <div class="form-horizontal">
        @Html.ValidationSummary(true)


        <div class="form-group">
            @Html.LabelFor(model => model.Entidad, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Entidades", (IEnumerable<SelectListItem>)ViewData["Entidades"], new { @class = "form-control" })
            </div>
        </div>


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

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

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

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-primary" />
                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-white"})
            </div>
        </div>
    </div>
}

                </div>
            </div>
        </div>
    </div>
 </div>

and I have this controller 我有这个控制器

public class PropiedadesController : Controller
    {
        private AppDataContext db = new AppDataContext();

        public ActionResult SelectCategory()
        {
            List<SelectListItem> items = new List<SelectListItem>();
            foreach(Entidad entidad in db.Entidades.ToList())
            {
                items.Add(new SelectListItem { Text = entidad.Nombre, Value = entidad.Id.ToString() });
            }

            ViewBag.Entidades = items;
            return View();
        }

        // GET: /GlobalAdmin/Propiedades/
        public ActionResult Index()
        {
            return View(db.Propiedades.ToList());
        }

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

        // GET: /GlobalAdmin/Propiedades/Create
        public ActionResult Create()
        {
            AppDataContext db = new AppDataContext();
            var entidades = from c in db.Entidades select c;
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (Entidad entidad in entidades)
            {
                items.Add(new SelectListItem { Text = entidad.Nombre, Value = entidad.Id.ToString() });

            }
            ViewBag.Entidades = items;
            return View();
        }

        // POST: /GlobalAdmin/Propiedades/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 ActionResult Create([Bind(Include="Id,Codigo,Nombre,TipoDeDatos")] Propiedad propiedad)
        {
            if (ModelState.IsValid)
            {
                db.Propiedades.Add(propiedad);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(propiedad);
        }

        // GET: /GlobalAdmin/Propiedades/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            AppDataContext db = new AppDataContext();              
            var entidades = from c in db.Entidades select c;
            List<SelectListItem> items = new List<SelectListItem>();
            foreach (Entidad entidad in entidades)
            {
                items.Add(new SelectListItem { Text = entidad.Nombre, Value = entidad.Id.ToString() });

            }
            ViewBag.Entidades = items;

            Propiedad propiedad = db.Propiedades.Find(id);
            if (propiedad == null)
            {
                return HttpNotFound();
            }
            return View(propiedad);
        }

        // POST: /GlobalAdmin/Propiedades/Edit/5
        // 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 ActionResult Edit([Bind(Include="Id,Codigo,Nombre,TipoDeDatos")] Propiedad propiedad)
        {
            if (ModelState.IsValid)
            {
                db.Entry(propiedad).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(propiedad);
        }

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

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

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

However when I created a row, the database shows the foreign KEY as null (Entidad ID) 但是,当我创建一行时,数据库将外键显示为空(Entidad ID)

What am I missing here? 我在这里想念什么?

Propiedad Model is this Propiedad模型是这个

 public class Propiedad
    {
        [Key]
        public int Id { get; set; }

        public virtual Entidad Entidad { get; set; }

        public string Codigo { get; set; }
        public string Nombre { get; set; }
        public string TipoDeDatos { get; set; }
    }

Screenshot 屏幕截图

http://screencast.com/t/B5m6X8mtbSdd http://screencast.com/t/B5m6X8mtbSdd

Update 1: I modified the controller like this: 更新1:我像这样修改控制器:

public ActionResult Create() { ViewBag.Entidad = new SelectList(db.Entidades, "Id", "Nombre"); public ActionResult Create(){ViewBag.Entidad = new SelectList(db.Entidades,“ Id”,“ Nombre”); return View(); 返回View(); } }

and the view like this: 和这样的视图:

   <div class="form-group">
            @Html.LabelFor(model => model.Entidad, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Entidad.Id, new SelectList(ViewBag.Entidad, "Id", "Nombre", Model.Entidad.Id), "Seleccionar", new { @class = "form-control" })
            </div>
        </div>

However on the view I get an object reference not set to an instance of an object. 但是,在视图上,我得到的对象引用未设置为对象的实例。

This is the entity model 这是实体模型

    public class Entidad
    {
        [Key]
        public int Id { get; set; }
        public string Nombre { get; set; }

        public virtual ICollection<Propiedad> Propiedades { get; set; }
}

and the property model 和财产模型

 public class Propiedad
    {
        [Key]
        public int Id { get; set; }

        public virtual Entidad Entidad { get; set; }

        public string Codigo { get; set; }
        public string Nombre { get; set; }
        public string TipoDeDatos { get; set; }
    }

I don't see where print the dropdownlist in your view. 我在您的视图中看不到下拉列表的打印位置。

Well try this: In your controller load the list: 好吧,尝试一下:在控制器中加载列表:

ViewBag.entities = new SelectList(db.Entidades, "Id", "Nombre") ;

And then in your view inside the form: 然后在您的表单中查看:

@Html.DropDownListFor(model => model.Entidad.Id, (SelectList) ViewBag.entities, "Seleccionar")

Model equivalent a your class: Propiedad 与您的课程相当的模型: Propiedad

With this you will automatically receive the object with the selected value. 这样,您将自动接收具有所选值的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM