Posting results when checkbox is checked in MVC 4

2019-09-01 04:47发布

问题:

I've been asked to repost this question with more detail.

I'm new to MVC and I'd appreciate any supporting explanations although I am quite grounded in .NET development.

Scenario

I have a calendar that posts to a calendar with information when it's selected. It looks like this:

@foreach (var OfflineCalendar in Model.OfflineCalendars.Skip(1))
{
    <li data-name="@OfflineCalendar.Name" data-val="@OfflineCalendar.Id">@Html.ActionLink(OfflineCalendar.Name, "Index", new { Id = OfflineCalendar.Id }, new { @class = "location" })</li>
 }

The calendar only returns data for a month which passes some data to a ContentResult method.

I've added a Checkbox for archived data.

<label>
    Archived
    @Html.CheckBox("checkedArchive")
</label>

My Task

I want to add an archived button where a user can view historic data. If this checkbox is checked, it changes some parameters in the ContentResult Data method.

The Dilemma

In .NET I would easily check for whether a checkbox is checked and fire an event based on the calendar that's selected. I'm struggling to do the MVC equivalent.

All I want to do is check if it's checked WHEN a calendar location is selected. If it is, return a bool of true or false. Which will affect the ContentResult.

I don't want to use Ajax. I just simply want to check whether a checkbox is checked when a location is selected. That's all.

Here's the related question I asked: clicky

Thank you for reading.

回答1:

It sounds like you want to do all of this server side through your existing code and just want to access the value of the checkbox.

If that is correct, I would modify the ViewModel to include a boolean "IncludeArchived" and then add it to your page:

 @Html.CheckBoxFor(model => model.IncludeArchived)

When you submit your form the value should be included in your Model.

Alternatively, you could check Request.Form["checkedArchive"] on the server side and parse that into a boolean.



回答2:

you need to write checkbox event in jquery and check if checkbox is checked post the form and return content from server else don't post the form.

Like this:

View:

<form action="" method="POST" id="MyForm">
    <label>
        Archived
        @Html.CheckBox("checkedArchive")
    </label>
</form>

Jquery:

$('#checkedArchive').on('change',function(){


if(this.checked)
{

$('#MyForm').submit();

}


});