asp.net-mvc - 绑定(bind)到 ProfileCommon 的 ASP.NET 模型

标签 asp.net-mvc

我想知道是否有一个很好的示例来说明如何使用模型绑定(bind)在 MVC 中编辑 ASP.NET 配置文件设置。

目前我有:

  • 派生自 ProfileBase 的自定义 ProfileCommon 类。
  • 强类型 View (ProfileCommon 类型)
  • 在与 ProfileCommon 和关联 View 一起工作的 Controller 上获取和发布操作。 (见下面的代码)。

查看个人资料详细信息有效 - 表单显示所有字段均已正确填充。

但是保存表单会出现异常:System.Configuration.SettingsPropertyNotFoundException:未找到设置属性“FullName”。

考虑到这一点是有道理的,因为模型绑定(bind)将实例化 ProfileCommon 类本身,而不是获取 httpcontext 之一。此外,保存可能是多余的,因为我认为配置文件在修改时会自动保存 - 在这种情况下,即使验证失败也可能如此。对吧?

无论如何,我目前的想法是,我可能需要为模型绑定(bind)创建一个单独的 Profile 类,但当我已经有一个非常相似的类时,这似乎有点多余。

有什么好的例子吗?

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Edit()
    {
        return View(HttpContext.Profile);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(ProfileCommon p)
    {
        if (ModelState.IsValid)
        {
            p.Save();
            return RedirectToAction("Index", "Home");
        }
        else
        {
            return View(p);
        }
    }

最佳答案

当您说 ProfileCommon 实例是在后期场景中从头开始创建(而不是从 HttpContext)时,这听起来是正确的 - 这就是 DefaultModelBinder 所做的:它根据其默认构造函数创建该类型的新实例。

我认为您可以通过创建如下所示的自定义 IModelBinder 来解决此问题:

public class ProfileBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        return controllerContext.HttpContext.Profile;
    }
}

您可能需要进行一些转换以使其适合您的个人资料类别。

要使用这个 ProfileBinder,您可以像这样将它添加到您的编辑 Controller 操作中:

public ActionResult Edit([ModelBinder(typeof(ProfileBinder))] ProfileCommon p)

关于asp.net-mvc - 绑定(bind)到 ProfileCommon 的 ASP.NET 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1366125/

相关文章:

c# - 表单提交后 MVC 从 View 返回填充模型

c# - 使用 StructureMap 注入(inject)自定义成员提供程序

asp.net-mvc - Visual Studio for Mac-错误 CS1902

c# - 我应该将验证逻辑放在 POCO 中吗?

jquery - JSON Post 调用错误函数

c# - 如何使用 ASP.NET MVC 进行 HTTP 调用?

c# - 未提供所需的防伪 token 或该 token 无效

asp.net-mvc - Telerik mvc 网格 ForeignKey 列

c# - 如何将带有某些 xml 类型列的行批量插入数据库?

asp.net-mvc - 按 PK 与用户名性能搜索用户