asp.net mvc save checkbox value to database

2020-04-17 07:21发布

问题:

I have a simple mvc project consisting of one table named Persons and that table has some attributes like name, age, surname and so on.

I Recently added an attribute to table which is type of bit in SQL and bool in C# and for me it represents some status. If it is ok I put that status to true or false.

In one controller I create an index view of my Persons in the database and I display the status as a checkbox. That is working ok. What I want to do is to change the status if I click on that checkbox instead of using an edit view for all of the atributes. I just want to save checkbox value from my index view to database.

Some people advised me to create an action in my controller like so:

public ActionResult Save(int id, bool status){}

Where id is id of my person in db and status is a value of the checkbox I clicked.

So how do I call that function with jquery, ajax or javascript and send those params? I am not so good with ajax and a little bit afraid of it :)

And one more thing I manage to show checkbox value corectly from my databse only in this way:

@Html.CheckBox("somename", item.Status)
        <input name="somename" type="hidden" value="false"/>

Any help or advice or sending me to good direction is good!

回答1:

You have several options. One way would be to place the checkboxes in a (normal) form and then use the jQuery Form plugin to Ajaxify the form:

@using(Html.BeginForm()) {
    @Html.Checkbox(...)
}

<script type="text/javascript">
    $(document).ready(function () {
        $('form').ajaxForm({
            success: Saved,
            error: HandleError
        });
    });

    function Error(response, status, err) {
        // code to handle error here
    }

    function Saved(responseText, statusText, xhr, $form) {
        // code to handle succes, if any
    }
</script>

You could, of course, use an @Ajax.BeginForm as well, but this has the advantage of being easily downgradable. Just remove the jQuery form initialisation and you got yourself a regular form : )

Another possibility is to simply use an @Ajax.ActionLink. I wrote a blog post on how to deal with Ajax.ActionLink that I think will help you out.

The signature for your controller action on your question looks correct:

public ActionResult Save(int id, bool status){}

Another options is actually to create a Settings view model (call it what you will), and in there just have a bunch of bool properties to represent the checkboxes:

public class Settings
{
    public bool Status { get; set; }
    // more properties here
}

then you can bind your action to the Settings object:

public ActionResult Save(int id, Settings settings){}

This will come in handy in case you end up having multiple checkboxes to bind.