0

I have a requirement to create an editor template in ASP.NET for model of type Boolean. The template should consist of one button that will display either '=' or '!=' as it's value. E.g., Boolean Button

When the user clicks the button it should inverse the boolean and submit the form.

I initiate the template with this line,

@Html.EditorFor(m => m.Negate, "MyBooleanTemplate")

I have the custom editor template working if I use a TextBox as the input and type in False or True when the form submits the model is picking up the new value.

@model Boolean
@Html.TextBoxFor(m => m)

However, when I am trying to implement the custom template the model never picks up the change in value.

@model Boolean
@{
    string propertyName = Html.ViewData.ModelMetadata.PropertyName;
    string id = Html.IdForModel();
    string displayValue = Model ? "!=" : "=";
    string currentValue = Model.ToString();
    string changeValue = (!Model).ToString();
}

<button type="button" id="@id" name="@propertyName" value="@currentValue" onclick="this.value = '@changeValue'; this.form.submit();" class="btn btn-sm">@displayValue</button>

Am I right in thinking I need to have an element with the id, name and value attributes populated for the model binding to work?

1 Answer 1

0

I managed to solve it by editing a hidden field.

The editor template,

@model Boolean
@{
    string id = Html.IdForModel();
    string displayValue = Model ? "!=" : "=";
    string currentValue = Model.ToString();
    string changeValue = (!Model).ToString();
}
<input asp-for="@Model" type="hidden" />
<button type="submit" onclick="document.getElementById('@id').value = '@changeValue'">@displayValue</button>

And invoked with,

@Html.EditorFor(m => m.Negate, "BooleanNegate", new { @class = "btn btn-sm" })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.