怎么了? DropDownList Asp.Net Mvc C#

时间:2018-08-07 19:10:15

标签: c# asp.net-mvc

[HttpGet] ActionResult编辑

Model model = dbContext.Table.Find(id);
ViewBag.MyID = new SelectList(dbContext.Table, "id", "value", model.value);

查看修改

@Html.DropDownList("MyID", (IEnumerable<SelectListItem>)ViewBag.MyID)

[HttpPost] ActionResult编辑

public ActionResul Edit(..., string MyID)

我的模型

[Table("tb_estados_uf")]
public class Estado
{
    [Key]
    public int uf_id { get; set; }

    [Display(Name = "Estado")]
    public string uf_estado { get; set; }

    [Display(Name = "UF")]
    public string uf_sigla { get; set; }

    public IEnumerable<Estado> ufIE { get; set; }
}

这是我视图的顶部:

@model Oficial.Models.Candidato

我的控制器

public ActionResult Edit([Bind(Include ="(Candidato's Columns)..., uf_id (FK)")] Candidato objCandidato, FormCollection fc, HttpPostedFileBase file, string MyID)

问题在于此参数,他总是1

即使它与我数据库的最后一条记录一起记录。

有什么我忘了吗?

对不起,我的英语

1 个答案:

答案 0 :(得分:0)

您的模型应该没有展示属性

[Table("tb_estados_uf")]
public sealed class Estado
{
    [Key]
    public int uf_id { get; set; }

    public string uf_estado { get; set; }

    public string uf_sigla { get; set; }

    public IEnumerable<Estado> ufIE { get; set; }
}

然后您创建一个单独的视图模型,以便从用户那里收集数据。

public sealed class EstadoViewModel
{
  public int uf_id { get; set; }

  [Display(Name = "Estado")]
  public string uf_estado { get; set; }

  [Display(Name = "UF")]
  public string uf_sigla { get; set; }

  public IEnumerable<Estado> ufIE { get; set; }
}

您的新视图模型:

public sealed class Candidato
{
  public int Id { get; set; }
  public string Phone { get; set; }
  public string OtherField { get; set; }
  public EstadoViewModel EstadoVM { get; set; }
}

然后在您的视图顶部:

@model Oficial.Models.Candidato

然后在您的视图中添加下拉控件:

@Html.DropDownListFor(m => m.EstadoVM.uf_sigla, Model.EstadoVM.ufIE, new { @class = "form-control input-sm" })

最后在您的控制器中:

[HttpPost]
public ActionResul Edit(Candidato model) 
{
  // Code action here
}