ASP MVC 4:DropDownListFor的请求值 [英] ASP MVC 4: Request value of DropDownListFor

查看:107
本文介绍了ASP MVC 4:DropDownListFor的请求值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类多到很多,首先是Anuncios,第二个SubCategorias

I have two classes many-to-many the first is "Anuncios" and the second "SubCategorias"

public class Anuncios {
    public int AnuncioId {get;set;}
    public string Titulo {get;set;}
    public ICollection<SubCategorias> SubCategorias {get;set;}
}

public class SubCategorias {
    public int SubCategoriaId {get;set;}
    public string Nome {get;set;}
    public ICollection<Anuncios> Anuncios {get;set;}
}

在DAL层我做的方法保存在DB的Anuncio。

In DAL layer I did method to save the "Anuncio" in DB.

public void Salvar(Anuncio entidade)  {
     entidade.SubCategorias = entidade.SubCategorias.Select(subcat => _contexto.SubCategorias.FirstOrDefault(x => x.SubCategoriaId == subcat.SubCategoriaId)).ToList();
     _contexto.Anuncios.Add(entidade);
     _contexto.SaveChanges();
}

我创建行动创建

private readonly Context _ctx = new Context();

public ActionResult Create()
{
    var model = new Anuncios {SubCategorias = _ctx.SubCategorias.ToList()};
    return View(model);
}

在查看我做的DropDownList与SubCategorias

In View I made DropDownList with "SubCategorias":

@Html.LabelFor(model => model.SubCategorias)
@Html.DropDownListFor(model => model.SubCategorias, new SelectList(Model.SubCategorias, "SubCategoriaId", "Nome"))

该DropDownListFor填充了sucess ..

The DropDownListFor is populated with sucess..

精细....

但是,当提交形成DropDownListFor选择的值不会传递给方法创建。该anuncio.SubCategorias为空!

But when submit form the value selected in DropDownListFor not pass to method Create. The anuncio.SubCategorias is null!

private readonly AnunciosDal _anuncio = new AnunciosDal();

[HttpPost]
public ActionResult Create(Anuncio anuncio)
{
    _anuncio.Salvar(anuncio);
    return View(anuncio);
}

我在各种论坛上寻求解决方案,但没有找到

I have sought in various forums the solution, but could not find

有人帮我?!

对不起我的英语RS ...

Sorry about my english rs...

感谢您!
法布里西奥·奥利维拉

Thank You! Fabrício Oliveira

推荐答案

DropDownListFor的第一个参数必须保持的所选值,其中第二个参数包含列表中的对象:

The first parameter of DropDownListFor needs to be the object holding the selected value, where the second parameter contains the list:

@Html.DropDownListFor(model => model.SOME_ID_FOR_SELECTED_VALUE, 
                  new SelectList(Model.SubCategorias, "SubCategoriaId", "Nome"))

目前你还例如映射同一列表的第一个属性。你应该使用一个ID喜欢@Maess建议,然后通过绑定:

Currently the example you have also maps the same list as the first property. You should use an ID like @Maess suggested, and then bind it via:

@Html.DropDownListFor(model => model.SubCategoriaID, new SelectList(Model.SubCategorias, "SubCategoriaId", "Nome"))

选择数值,然后将它张贴回服务器这个领域SubCategoriaID

Selecting a value will then post it back to the server to this SubCategoriaID field.

这篇关于ASP MVC 4:DropDownListFor的请求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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