0

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();

1 Answers1

0

checkbox and file are special parts of a form, they could be a simple string value or an array, JQuery cannot know what it is, unless you specify a special attribute to check.

combine the 2 code:

  1. https://gist.github.com/oswaldoacauan/7580474
  2. jQuery serialize does not register checkboxes

    (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);
    

then use it:

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

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

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

});

to make the above extension work widely in the whole project, probably you need to render 1 more attribute in html: data-multiple=true/false (Default is false). then check this attribute in extension: if it's true, serialize values to array, otherwise to a bool or file value, so it would match all your viewmodels.

Dongdong
  • 2,208
  • 19
  • 28