在 lambda 表达式中使用三元运算符会产生"Only Assignment, Call, Increment, Decrement ... as a statement"异常



我收到"只有赋值、调用、递增、递减、等待表达式和新对象表达式可以用作语句"错误,并使用以下三元运算符:

@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 中实现简洁的条件逻辑? 语法有问题。

你可以这样做:

@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" }))};

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

不要使用使用 lambda 的Html.BeginForm<>通用扩展。 代码将如下所示:

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

或者正如威尔所建议的那样,将逻辑向上移动:

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

相关内容

最新更新