【问题标题】:Using a ternary operator in a lambda expression gives "Only Assignment, Call, Increment, Decrement ... as a statement" exception在 lambda 表达式中使用三元运算符会给出“仅将赋值、调用、递增、递减......作为语句”异常
【发布时间】:2018-06-20 02:59:45
【问题描述】:

以下三元运算符出现“只有赋值、调用、递增、递减、等待表达式和新对象表达式可以用作语句”错误:

@using (Html.BeginForm<AssetController>(
           x => (Model.Id == -1 ? x.Create() : x.Edit(Model.Id) ) , 
           FormMethod.Post, 
           new { @class = "form-horizontal", id = "save-assetType-form" }))

以下代码出现“无法将带有语句体的 lambda 表达式转换为表达式树”错误:

@using (Html.BeginForm<AssetController>(x => 
    {
        if (Model.Id == -1) 
            x.Create();
        else 
            x.Edit(Model.Id);

    }, FormMethod.Post, new { @class = "form-horizontal", id = "save-assetType-form" }))
}

有没有办法在我的 lambda 中实现简洁的条件逻辑?语法有问题。

【问题讨论】:

  • 不。 BeginForm 正在解析表达式树,而不是执行它。它不明白你在做什么。将 if 逻辑移到 Html.BeginForm 调用之外。
  • 想...谢谢。

标签: c# asp.net-mvc razor lambda


【解决方案1】:

你可以这样做:

@using (Html.BeginForm<AssetController>(
    //But you have to specify one of the delegate's type.
    Model.Id == -1 ? x => x.Create() : (Action<YourInputType>)(x => x.Edit(Model.Id)), 
    FormMethod.Post, 
    new { @class = "form-horizontal", id = "save-assetType-form" }))};

但是,我建议您按照旧的方式进行操作:

if (Model.Id == -1)
    @using (Html.BeginForm<AssetController>(x => x.Create(), 
    FormMethod.Post, 
    new { @class = "form-horizontal", id = "save-assetType-form" }))};
else
    @using (Html.BeginForm<AssetController>(x => x.Edit(Model.Id), 
    FormMethod.Post, 
    new { @class = "form-horizontal", id = "save-assetType-form" }))};

【讨论】:

  • 我不懂asp语法,不正确不要杀我.. ;)
  • 很遗憾,您不能将 if/else 包裹在 @using 块周围
【解决方案2】:

我想我会回答我自己的问题,以防有人来这里寻找相同的答案。由于这是不可能的,有几种方法可以做到:

不要使用使用 lambda 的 Html.BeginForm&lt;&gt; 通用扩展。代码看起来像:

Html.BeginForm( (Model.Id == -1 ? "Create" : "Edit"), ...)

或者按照 Will 的建议,将逻辑上移:

Expression<Action<AssetController>> action = x => x.Create();
if (Model.Id != -1)
{
    action = x => x.Edit(Model.Id);
}
using (Html.BeginForm(action, ...)

【讨论】:

    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2016-10-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多