简体   繁体   中英

Getting Checkbox Value in ASP.NET MVC

I'm working on an ASP.NET MVC app. This app has a basic form. The model for my form looks like the following:

public partial class User
{
    public bool Addon { get; set; }
}

In my form, I have the following HTML.

<div class="form-group">
    @Html.LabelFor(model => model.Addon, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="checkbox">
            @Html.EditorFor(model => model.Addon)
            @Html.ValidationMessageFor(model => model.Addon, "", new { @class = "text-danger" })
        </div>
    </div>
</div>

I currently don't have any code for the Addon in the controller.

I want to check if Checkbox was checked inside a different HTML to show hidden links that would only be available if the checkbox was checked.

How would I able to check it if the if statement was in a different HTML page? Because the checkbox would be checked at the moment at User Creation. Then once logging in, the index page would depend if the checkbox it checked or not.

An example would be

if (Addon == True)
{
    <div class="col-md-4">
        <p><a onclick="@("window.location.href='" + @Url.Action("Create", 
        "Users") + "'");" class="btn btn-primary btn-lg">Add User &raquo; 
         </a></p>
     </div>
}

Any ideas on how I could go about this? Thank you.

You can set id of checkbox and use Javascript to control if it's check like this:

@Html.EditorFor(model => model.Addon, new { id ="chkAddon" })

Then use is(":checked") in Javascript would be like:

if ($('#chkAddon').is(":checked"))
{
    <div class="col-md-4">
        <p><a onclick="@("window.location.href='" + @Url.Action("Create", 
        "Users") + "'");" class="btn btn-primary btn-lg">Add User &raquo; 
         </a></p>
    </div>
}
<div class="form-group">
    @Html.LabelFor(model => model.Addon, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="checkbox">
            @Html.EditorFor(model => model.Addon,"", new { @class = "check-btn" })
            @Html.ValidationMessageFor(model => model.Addon, "", new { @class = "text-danger" })
        </div>
    </div>
</div>

<a id="link" href="#"  style="display:none;">Link</a>

<script type="text/javascript">

    $(document).ready(function () {

        $(".check-btn").change(function () {
            if (this.checked) {
                $("#link").css("display", "block");
            }
            else {
                $("#link").css("display", "none");
            }
        });


</script>

you want to safety, need you use jquery ajax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM