我得到了一个"只有分配,调用,增量,减量,等待表达和新对象表达式可以用作语句"以下三元运算符出错:
@using (Html.BeginForm<AssetController>(
x => (Model.Id == -1 ? x.Create() : x.Edit(Model.Id) ) ,
FormMethod.Post,
new { @class = "form-horizontal", id = "save-assetType-form" }))
&#34;带有语句体的lambda表达式无法转换为表达式树&#34;以下代码出错:
@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中实现简洁的条件逻辑?语法有问题。
答案 0 :(得分:0)
你可以这样做:
@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" }))};
答案 1 :(得分:0)
我想回答我自己的问题,为了完整性,万一有人来这里寻找相同的答案。由于不可能,有几种方法可以做到:
不要使用使用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, ...)