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

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

rokkerboci
2#
rokkerboci Reply to 2018-01-10 21:20:49Z

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" }))};
gdbj
3#
gdbj Reply to 2018-01-10 21:39:20Z

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, ...)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.336347 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO