DropDown不显示之前选择的内容&保存

时间:2013-07-12 14:04:38

标签: c# asp.net-mvc

客户可以查看他们的客户详细信息页面,他们可以在这里更改预先录制的交付运行(如果他们也愿意)我有一个下拉列表,其中包含交付运行的城镇:

<div class="editor-label">@Html.DropDownListFor(model => model.DeliveryRunList, Model.DeliveryRunList)</div>

当客户资料加载时,它会在下拉列表中显示正确的城镇(从DB中读取,这是他们之前在注册时选择的)。

但是,如果他们更改城镇并保存,则用户将返回主页,新选择的拖车将保存到DB。但是,如果用户返回到客户资料页面,则下拉列表会显示先前选择的城镇,而不是刚刚选择并保存到数据库的新城镇。它是否存储在某个地方的缓存中。

为什么不更新到DB中的实际内容?

代码隐藏:

CustomerPart custPart = _custService.Get(custId);

if (DeliveryRunList.HasValue)
{
    custPart.DeliveryRun_Id = DeliveryRunList.Value;
}

_custService.Update(custPart);

由于

1 个答案:

答案 0 :(得分:0)

我认为model是一个CustomerPart实例,您已经以这种方式或多或少地定义了它。

public class CustomerPart
{
    public int DeliveryRun_Id {get; set;}
    public SelectList(or some IEnumerable) DeliveryRun_Id
}

我觉得你的代码没有更新数据库,因为你使用了错误的属性。第一个lambda表达式应为model => model.TheAttributeYouWantToUpdate,在本例中为DeliveryRun_Id

所以它应该是:

@Html.DropDownListFor(model => model.DeliveryRun_Id, Model.DeliveryRunList)

而不是

@Html.DropDownListFor(model => model.DeliveryRunList, Model.DeliveryRunList)

甚至不清楚控制器中的代码在哪里:

CustomerPart custPart = _custService.Get(custId);

if (DeliveryRunList.HasValue)
{
    custPart.DeliveryRun_Id = DeliveryRunList.Value;
}

_custService.Update(custPart);

执行此操作的常用方法是使用两个同名的方法进行编辑,一个用于HttpGet,一个用于HttpPost,并在剃刀视图中使用@Html.BeginForm()进行更新,而不是更新信息控制器。

示例:

        public ActionResult Edit(int id = 0) {
            InvestmentFund Fund = InvestmentFundData.GetFund(id);
            return Fund == null ? (ActionResult)HttpNotFound() : View(Fund);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(InvestmentFund Fund)
        {
            if (ModelState.IsValid)
            {
                InvestmentFundData.Update(Fund);
                return RedirectToAction("List");
            }
            return View(Fund);
        }

在视图中

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

        @* For the attributes of your model *@
        @Html.LabelFor ... 
        @Html.EditorFor ...
        @Html.ValidationMessageFor ...

        <input type="Submit"m value="Save">
    }
相关问题