Home Using a ternary operator in a lambda expression gives "Only Assignment, Call, Increment, Decrement ... as a statement" exception

# Using a ternary operator in a lambda expression gives "Only Assignment, Call, Increment, Decrement ... as a statement" exception

gdbj
1#
gdbj Published in 2018-01-10 20:55:08Z
 I'm getting a "Only Assignment, Call, Increment, Decrement, Await Expression and New Object expressions can be used as a statement" error with the following ternary operator: @using (Html.BeginForm( x => (Model.Id == -1 ? x.Create() : x.Edit(Model.Id) ) , FormMethod.Post, new { @class = "form-horizontal", id = "save-assetType-form" }))  And a "A lambda expression with a statement body cannot be converted to an expression tree" error for the following code: @using (Html.BeginForm(x => { if (Model.Id == -1) x.Create(); else x.Edit(Model.Id); }, FormMethod.Post, new { @class = "form-horizontal", id = "save-assetType-form" })) }  Is there a way to achieve concise conditional logic in my lambda here? Having trouble with the syntax.
rokkerboci
2#
 You could do it like this: @using (Html.BeginForm( //But you have to specify one of the delegate's type. Model.Id == -1 ? x => x.Create() : (Action)(x => x.Edit(Model.Id)), FormMethod.Post, new { @class = "form-horizontal", id = "save-assetType-form" }))};  However, I would recomend just doing it the good old way: if (Model.Id == -1) @using (Html.BeginForm(x => x.Create(), FormMethod.Post, new { @class = "form-horizontal", id = "save-assetType-form" }))}; else @using (Html.BeginForm(x => x.Edit(Model.Id), FormMethod.Post, new { @class = "form-horizontal", id = "save-assetType-form" }))}; 
 I'll answer my own question I guess, for completeness in case someone comes here looking for the same answer. Since it's not possible, there are a couple ways to do it: Don't use the Html.BeginForm<> generic extension that uses lambda. Code would look something like: Html.BeginForm( (Model.Id == -1 ? "Create" : "Edit"), ...) Or as Will suggests, move the logic up: Expression> action = x => x.Create(); if (Model.Id != -1) { action = x => x.Edit(Model.Id); } using (Html.BeginForm(action, ...)