【问题标题】:Model Binding in NancyNancy 中的模型绑定
【发布时间】:2013-12-27 05:27:22
【问题描述】:

由于某种原因,我无法让 NancyFx 绑​​定到我的网页模型。如果这很重要,我会自行托管。

这是我的路线代码:

Get["/fax.html"] = p =>
{
    FaxModel model = new FaxModel();

    var foundType = processes.Where(proc => proc.GetType().ToString().Contains("FaxServer"));
    if(foundType.First() != null)
    {
        bool enabled = Boolean.Parse(WorkflowSettings.GetValue(foundType.First().GetProcessName(), "Enabled"));
        bool deleteAfterSuccess = Boolean.Parse(WorkflowSettings.GetValue(foundType.First().GetProcessName(), "DeleteWorkflowItemsAfterSuccess"));

        model.EnableFaxes = enabled;
        model.DeleteFaxes = deleteAfterSuccess;

        // Bind the data
        this.BindTo<FaxModel>(model);
    }

    return View["fax.html"];
};

这是我的模型:

[Serializable]
public class FaxModel
{
    public bool EnableFaxes { get; set; }
    public bool DeleteFaxes { get; set; }
}

现在这是我的 HTML 代码:

<div id="body">
  <form method="post" action="fax.html" name="fax_settings">
  <ul>
    <li>
      <input name="EnableFaxes" value="true" type="checkbox">Automated Faxing Enabled
    </li>
    <li>
      <div style="margin-left: 80px;"><input name="DeleteFaxes" value="true" type="checkbox">Delete workflow items when fax is successful</div>
    </li>
  </ul>
  <button name="Save">Save</button>
  </form>
</div>

我不明白为什么它根本没有填充这些复选框。有人有想法吗?

【问题讨论】:

    标签: c# .net nancy


    【解决方案1】:

    您正在使用 BindTo 覆盖设置。删除该调用并返回一个带参数的视图。

    this.Bindthis.BindTo 用于将输入参数(查询、表单、请求正文)绑定到模型,而不是将数据绑定到视图。

    Get["fax"] = p =>
    {
        FaxModel model = new FaxModel();
    
        var foundType = processes.Where(proc => proc.GetType().ToString().Contains("FaxServer"));
        if(foundType.First() != null)
        {
            bool enabled = Boolean.Parse(WorkflowSettings.GetValue(foundType.First().GetProcessName(), "Enabled"));
            bool deleteAfterSuccess = Boolean.Parse(WorkflowSettings.GetValue(foundType.First().GetProcessName(), "DeleteWorkflowItemsAfterSuccess"));
    
            model.EnableFaxes = enabled;
            model.DeleteFaxes = deleteAfterSuccess;
        }
    
        return View["fax", model];
    };
    

    或者,只要您的模型类遵循约定,您就可以这样做:

    return View[model];
    

    请参阅view engine examples

    另外,你的 html 应该使用这样的模型属性:

    <input name="EnableFaxes" value=@Model.EnableFaxes type="checkbox">Automated Faxing Enabled
    

    【讨论】:

    • 这些似乎都不起作用。将我的代码更改为您发布的代码。验证数据库以确保我在模型值上分别有一个 true 和 false,当我进行完整的重建然后运行它时,它不会显示任何一个已选中。
    • 它不会像你拥有的那样工作。这是一个静态的html,没有办法替换参数。你需要一些视图引擎。查看我提供的示例链接。
    • 只要我输入来自引擎的数据,它就起作用了。文档并没有真正定义对此的绑定,这让我很失望。非常感谢!
    猜你喜欢
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    相关资源
    最近更新 更多