MVC-3 DropdownList或DropdownListFor - 无法在控制器POST中保存值 [英] MVC-3 DropdownList or DropdownListFor - Can't save values in controller POST

查看:121
本文介绍了MVC-3 DropdownList或DropdownListFor - 无法在控制器POST中保存值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了几个小时(或几天),但尚未找到解决方案。我想用一个DropdownListFor编辑一个客户,使用正确的预选值进行称呼。

I searches for hours (or days) and didn't find a solution yet. I want to edit a customer with a DropdownListFor for the salutation with the right preselected value.

我有3个实体(数据库第一个概念,这不是我自己的设计...):客户,地址,称呼

I've got 3 entities (Database first concept, this is not my own design...): customer, address, salutation

CUSTOMER有一个address_id(f_key),一个ADDRESS已经有一个salutation_id(f_key)。 ADDRESS以姓氏为例。在SALUTATION实体内部有一列sal1,其中包含所有可能的提示。

A CUSTOMER has an address_id (f_key) and an ADDRESS has got a salutation_id (f_key). The ADDRESS holds the first and last name for example. Inside the SALUTATION entity there is a column sal1 which holds all possible salutations.

现在,我想通过ViewModel编辑我的客户,如下所示:

Now, I want to edit my customer via a ViewModel which looks like this:

public class CustomerViewModel
{
    public CUSTOMER cust { get; set; }
    public SelectList salutationList { get; set; }

    CustomerRepository repository = new CustomerRepository();

    public CustomerViewModel(int id)
    {
        cust = repository.GetCustomerByIdAsQueryable(id).Single();
        salutationList = new SelectList(repository.GetSalutations(), cust.ADDRESS.SALUTATION.SAL1);
    }
    // Some more
}

CutsomerRepository方法:

The CutsomerRepository methods:

public class CustomerRepository
    {
        private MyEntities db = new MyEntities();

        public IQueryable<CUSTOMER> GetCustomerByIdAsQueryable(int id) {...}

        public IQueryable<CUSTOMER> GetCustomersByName(string firstName, string lastName, int maxCount)  {...}

        public List<string> GetSalutations()
        {
            var salutationList = new List<string>();
            var salutationListQry = from s in db.SALUTATION
                                    select s.SAL1;
            salutationListTemp.AddRange(salutationListQry);
            return salutationList;
        }
        // ...
    }

这是我的控制器方法:

[HttpPost]
public ActionResult CustomerData(int id, FormCollection fc)
{
    var vm = new CustomerViewModel(id);
    // Why do I need the following line?
    vm.cust = repository.GetCustomerByIdAsQueryable(id).Single();
    try
    {
        UpdateModel(vm, fc);
        repository.Save();
        return View("CustomerData", vm);
    }
    catch (Exception e)
    {
        return View();
    }
}

最后我的视图中的部分:

And finally the part from my View:

@model WebCRM.ViewModels.CustomerViewModel
@using (Html.BeginForm())
{
    // ...
    <div class="editor-label">
        @Html.Label("Salutation:")
        @Html.DropDownListFor(model => model.cust.ADDRESS.SALUTATION.SAL1, Model.salutationList)
        // @Html.DropDownList("Salutation", Model.salutationList)
    </div>
    <div class="editor-label">
    </div>
    <div class="editor-field">
        @Html.Label("Last name:")
        @Html.EditorFor(model => model.cust.ADDRESS.LASTNAME)
        @Html.ValidationMessageFor(model => model.cust.ADDRESS.LASTNAME)
    </div>
    <p>
        <input type="submit" value="Speichern" />
    </p>
}

更改和保存姓氏的工作正常。但是当保存称职时,它会将SALUTATION实体中的SAL1值更改为我在DropdownListFor中选择的值。我想要的是为我的客户更改ADDRESS实体内的salutation_id。为什么不工作?

Changing and saving last names works fine. But when saving the salutation it changes the SAL1 value in the SALUTATION entity to the one I've chosen in the DropdownListFor. What I want is to change the salutation_id inside the ADDRESS entity for my customer. Why isn't that working?

另一个奇怪的行为:当删除我的CustomerController中的标记行时,我甚至不能更改并保存姓氏。通常,CustimerViewModel的构造函数设置客户。那么为什么要在ViewModel中设置客户端代码呢?它是重复的,但必须在那里...

Another strange behavoior: When removing the marked line in my CustomerController, I can't even change and save the last name. Normally the constructor of the CustimerViewModel sets the customer. So why do I have to have the line of code for setting the customer inside my ViewModel? It's duplicated, but has to be there...

提前感谢

推荐答案

您需要在列表中选择属性。

You need to have Selected property in your list.

我可以向您展示我的工作示例:

I can show you my working example:

public static IEnumerable<SelectListItem> GetCountries(short? selectedValue)
    {
        List<SelectListItem> _countries = new List<SelectListItem>();
        _countries.Add(new SelectListItem() { Text = "Select country...", Value = "0", Selected = selectedValue == 0 });
        foreach (var country in ObjectFactory.GetInstance<DataRepository>().GetCountries())
        {
            _countries.Add(new SelectListItem()
            {
                Text = country.Name,
                Value = country.ID.ToString(),
                Selected = selectedValue > 0 && selectedValue.Equals(country.ID)
            });
        }
        return _countries;
    }  

在控制器中我将其存储到viewbag中:

In controller i store this into viewbag:

ViewBag.Countries = CompanyModel.GetCountries(0);

查看:

@Html.DropDownListFor(m => m.CompanyModel.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries)

这篇关于MVC-3 DropdownList或DropdownListFor - 无法在控制器POST中保存值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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