简体   繁体   中英

Pass variable from JavaScript to Controller

I have these check boxes, whose value i am getting using JQuery

<div>
    <p> Type:
        <label>
            <input type = "checkbox" name = "types[]" class="filterType" value="Single"/>Single
        </label>
        <label>
            <input type = "checkbox" name="types[]" class="filterType" value="Double"/>Double
        </label>
        <label>
            <input type = "checkbox" name="types[]" class="filterType" value="Suite" />Suite
         </label> </p>

   <input type="submit" value="filter" onclick="exefunction()" />
</div>  


<script>
function exefunction() {
        var checkedVals = $('.filterType:checkbox:checked').map(function () {
            return this.value;
        }).get();
        var typesAtt=checkedVals.join('-');
        }
</script>

How can I pass the typesAtt variable to my RoomController where I can apply filters from database. this is the Index.cshtml view

Same as with everything. You simply make http request, and pass whatever you want(as query parameter or part of body in case of a POST request).

If you make ajax request with jquery you will have to write a handler in your frontend application.

You need to keep the input elements inside a form tag and use the correct input element names.

@using(Html.BeginForm("Filter","Home"))
{
    <div>
        <p>
            Type:
            <label>
                <input type="checkbox" name="types" value="Single" />Single
            </label>
            <label>
                <input type="checkbox" name="types" value="Double" />Double
            </label>
            <label>
                <input type="checkbox" name="types" value="Suite" />Suite
            </label>
        </p>    
        <input type="submit" value="filter"  />
    </div>

}

Now in your Filter action method, you can have a parameter called types which is a string array type.

[HttpPost]
public ActionResult Filter(string[] types)
{
    // to do : Return something
}

When user submits the form, the types parameter will be populated with the value of selected check boxes. For example, if user selected "Single" and "Suite", types parameter will be a string array of 2 items, "Single" and "Suite"

The important thing to remember is, your input element's name should match with the action method parameter name.

At client side:

$.post("YourUrl",typesAtt,function(){
})

At Server side:

[HttpPost]
public ActionResult YourActionName(string data)
{

}

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