【问题标题】:MVC Model Binding Post Values Best PracticeMVC 模型绑定帖子值最佳实践
【发布时间】:2017-12-01 06:12:24
【问题描述】:

我试图弄清楚我所做的是否有缺陷或可以接受。具体来说,我质疑我在“时间框架”属性中的 POST 到控制器中返回的 NULL 值。 “时间框架”(单数)属性确实包含该值,所以一切都很好。但是,这仅仅是模型绑定的工作方式以及用于填充 DDL 的属性(时间帧)返回为 null 吗?这是最佳实践吗?我正在做的事情很好吗?这是发送不需要的值的问题吗……性能问题?

Timeframe = 用于在 Post 时将值返回给 Controller

时间范围 = 用于填充 DDL 值

视图上的下拉列表框:

@Html.DropDownListFor(m => m.Timeframe, Model.Timeframes)

型号:

public class ABCModel
{
    public List<SelectListItem> Timeframes { get; set; }
    public string Timeframe { get; set; }
}

控制器:

[HttpPost]
public void TestControllerMethod(ABCModel model)
{
    //this value is null. 
    var timeFrames = model.Timeframes;

    //this value is populated correctly
    var timeFrame = model.Timeframe;
}

【问题讨论】:

    标签: asp.net-mvc data-binding


    【解决方案1】:

    表单仅回发其成功控件的名称/值对。您已经为属性Timeframe 创建了一个表单控件,因此您可以在 POST 方法中获取所选选项的值。

    您没有(也不应该)为Timeframes 属性中的每个SelectListItem 的每个属性创建表单控件,因此在提交表单时不会在请求中发送与它相关的任何内容,因此值为Timeframesnull

    如果您因为ModelState 无效而需要返回视图,那么您需要像在GET 方法中那样重新填充TimeFrames 属性(否则您的DropDownListFor() 将抛出异常)。一个典型的实现可能看起来像

    public ActionResult Create()
    {
        ABCModel model = new ABCModel();
        ConfigureViewModel(model);
        return View(model);
    }
    
    [HttpPost]
    public ActionResult Create(ABCModel model)
    {
        if (!modelState.IsValid)
        {
            ConfigureViewModel(model);
            return View(model);
        }
        // Save and redirect
    }
    
    private void ConfigureViewModel(ABCModel model)
    {
        model.TimeFrames = ....; // your code to populate the SelectList
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多