首页 > 解决方案 > sending checkbox value true if checked else false with form object using jQuery in mvc

问题描述

I have a problem sending data to asp.net-mvc controller method

after ajax call every data from 'form' is sending to parameters of method, except "isActive" parameter of type "bool", whether 'checkbox' is selected or not it passing 'false' to mvc controller method.

$(".btnEntity").on("click", function () {
    var name = $(this).val();
    var _data = $("#myForm").serializeArray();
    var _url;
    if (name === "EntitySubmit") {
        _url = "/Home/EntitySend";
    }
    else {
        _url = "/Home/AdoSend";
    }
    var isActive=$("#isActive").prop('checked');
   
    var objdata = new FormData($("#myForm").get(0));
    objdata.append("ImageFile", $("#ImageFile").get(0).files);
    objdata.append("isActive", isActive);

    $.ajax({
        type: "post",
        url: _url,
        dataType: "json",
        //contentType: "application/json; charset=utf-8",
        processData: false,
        cache:false,
        contentType: false,
        data: objdata,
        success: function (response) {
            console.log(objdata);
            coursesData();
            console.log(_data);
        },
        error: function (error) {
            console.log(error);
        }
    });
});
<form name="myForm" id="myForm" method="post" class="form-inline" enctype="multipart/form-data">
    <div style="border-right:1px solid black">
        <input type="text" name="FirstName" id="FirstName" placeholder="Please enter First Name" class="form-control" /><br />
        <input type="text" name="LastName" id="LastName" placeholder="Please enter Last Name" class="form-control" /><br />
        <span class="radio-inline">
            <input type="radio" name="Gender" id="Gender" value="Male" class="radio" />
            <label class="control-label">Male</label>
        </span>
        <span class="radio-inline">
            <input type="radio" name="Gender" id="Gender" value="FeMale" class="radio" />
            <label>Female</label>
        </span>
        <span class="radio-inline">
            <input type="radio" name="Gender" id="Gender" value="Others" class="radio" />
            <label>Others</label>
        </span><br />
        <input type="text" id="Age" name="Age" placeholder="Please enter Age" class="form-control" /><br />
        <input type="date" name="DateofBirth" id="DateofBirth" class="form-control" /><br />
        <span id="CourseDDL"></span>
        <input type="file" name="ImageFile" id="ImageFile" class="form-control" /><br />
        <div class="form-group">
            <input type="checkbox" name="isActive" id="isActive" class="checkbox" />
            <label class="control-label" for="isActive">isActive</label>
        </div>
        <br />
        <br />
        <button value="EntitySubmit" name="btnEntity" id="btnEntity" class="btn btn-primary btnEntity">EntitySubmit</button>
        <span style="padding-left:10px;padding-right:10px">|</span>
        <button value="AdoSubmit" name="btnAdo" id="btnAdo" class="btn btn-success btnEntity">AdoSubmit</button>
    </div>
</form>

Controller:

public ActionResult EntitySend(userdetails objUser)
{
    byte[] bytes;
    using (BinaryReader br = new BinaryReader(objUser.ImageFile.InputStream))
    {
        bytes = br.ReadBytes(objUser.ImageFile.ContentLength);
    }

    using (MVCTutorialEntities db = new MVCTutorialEntities())
    {
        db.tblUsers.Add( new tblUser
        {
            FirstName = objUser.FirstName,
            LastName=objUser.LastName,
            Gender=Convert.ToBoolean(objUser.Gender),
            DateofBirth=objUser.DateofBirth,
            isActive= objUser.isActive,
            FileImage= new string(Encoding.ASCII.GetChars(bytes)),
        });
        db.SaveChanges();
    }

    return Json("Success....", JsonRequestBehavior.AllowGet);
}

model:

public class userdetails
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public int Age { get; set; }
    public DateTime DateofBirth { get; set; }
    public string Courses { get; set; }
    public HttpPostedFileBase ImageFile { get; set; }
    public bool isActive { get; set; }

}

I changed 'isActive' type to 'string' in model, then the value sending is taken as 'on' if "checkbox" is checked, else it takes 'off'. by doing that converting string to bool is not getting possible, like eg.,convert.toboolean(); or by bool.parse();

标签: c#jqueryasp.net-mvc

解决方案


checkbox并且file是表单的特殊部分,它们可以是简单的字符串值或数组,JQuery 无法知道它是什么,除非您指定要检查的特殊属性。

结合2个代码:

  1. https://gist.github.com/oswaldoacauan/7580474
  2. jQuery 序列化不注册复选框

    (function($) {
        $.fn.serializeAll = function() {
            var form = $(this),
                formData = new FormData(),
                formParams = form.serializeArray();
            //the following code return files array, but if could be 1 only to match your viewmodel
            $.each(form.find('input[type="file"]'), function(i, tag) {
                // check whether you need multiple files
                if($(tag)[0].attr('data-multiple')=='true'){
                   $.each($(tag)[0].files, function(i, file) {
                      formData.append(tag.name, file);
                   });
                }
                else{
                    //...get 1 file only
                }
            });
    
            //Checkbox: you need to debug this part, I just copied it 
            //check whether multiple options are checked , I won't code it here.
            formParams.concat(
                form.find('input[type=checkbox]:not(:checked)').map(
                  function() {
                    return {"name": this.name, "value": this.value}
                  }).get());
    
            $.each(formParams, function(i, val) {
                formData.append(val.name, val.value);
            });
    
            return formData;
        };
    })(jQuery);
    

然后使用它:

$(document).on("click", ".btnEntity", function (e){
    e.preventDefault();

    ....
    var $form = $(this).closest('form');// or $(this).parent('form');// or what ever
    ....

    $.ajax({
        ...
        data: $form.serializeAll();
        ...
    });

});

为了使上述扩展在整个项目中广泛使用,您可能需要在 html 中再渲染 1 个属性:(data-multiple=true/false默认为 false)。然后检查扩展中的这个属性:如果它是真的,将值序列化为数组,否则为布尔值或文件值,这样它就会匹配你所有的视图模型。


推荐阅读