gdbj
gdbj

Reputation: 17485

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

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<AssetController>(
           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<AssetController>(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.

Upvotes: 0

Views: 918

Answers (2)

gdbj
gdbj

Reputation: 17485

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<AssetController>> action = x => x.Create();
if (Model.Id != -1)
{
    action = x => x.Edit(Model.Id);
}
using (Html.BeginForm(action, ...)

Upvotes: 0

rokkerboci
rokkerboci

Reputation: 1167

You could do it like this:

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

However, I would recomend just doing it the good old way:

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

Upvotes: 0

Related Questions