【问题标题】:MVC3 - How to bind a FormCollection to a Model when creating a new database object?MVC3 - 创建新数据库对象时如何将 FormCollection 绑定到模型?
【发布时间】:2011-12-13 19:13:57
【问题描述】:

通过更新 ViewModel 时

[HttpPost]
public ActionResult Edit(int id, AddressChooserEnum addressChooser, string btnSubmit, FormCollection fc)
{
    var vm = new AddressViewModel(id, addressChooser, bool.FalseString);
    vm.Address = this.repository.GetAddressById(id, addressChooser);
    try
    {
        UpdateModel(vm);
        this.repository.Save();
        return RedirectToAction("Edit", "Customer", new { id = id });
    }
    catch (Exception e)
    {
        return View(vm);
    }
}

一切正常。但我无法与创作合作

[HttpPost]
public ActionResult Create(int id, AddressChooserEnum addressChooser, string btnSubmit, FormCollection fc)
{
    var vm = new AddressViewModel(id, addressChooser, bool.TrueString);
    this.repository.AddAddress(); //What here? It's the simple Add method which needs an Address object.
    this.repository.Save();
    return View(vm);
}

我正在尝试使用“空”地址创建 AddressViewModel。但是如何使用 FormCollection 存储它?我可以以某种方式将 FormCollection 绑定到新的 Address 对象吗?然后添加应该工作。 提前致谢。

【问题讨论】:

    标签: asp.net-mvc-3 http-post model-binding formcollection


    【解决方案1】:

    我不会使用表单集合。我只是尝试直接绑定到 View 模型。如果没有看到您的视图,很难告诉您您的操作应该是什么样子。查看这篇关于模型绑定的文章。它应该有帮助! Model Binding

    【讨论】:

    • 我已经尝试过了,但得到了错误,即 ViewModel 没有无参数构造函数。我添加了它,但现在 ViewModel 中缺少一些东西。有没有办法将参数传递给 vm 参数?像这样: public ActionResult Create(int id, AddressChooserEnum addressChooser, string btnSubmit, AddressViewModel vm(id, addressChooser)) {...}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多