skip to Main Content

I have a view :

@{
    ViewBag.Title = "Home Page";
}

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="~/Scripts/datatable/DataTables-1.10.20/css/dataTables.jqueryui.min.css" rel="stylesheet" />
    @section Scripts{

        <script src="~/Scripts/datatable/DataTables-1.10.20/js/jquery.dataTables.min.js"></script>
        <script src="~/Scripts/datatable/DataTables-1.10.20/js/dataTables.jqueryui.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#contenttable").DataTable({

                });

                $("#submitdata").click(function () {
                    var datatabledata = $("#datatble-form").serialize();
                    alert(datatabledata);
                    $.ajax({
                        url: "/Home/getData",
                        type: "POST",
                        data: { model: datatabledata },
                        success: function () {
                            alert('success');
                        },
                        error: function () {
                            alert('failure');
                        }
                    });
                });
            });
        </script>
    }
</head>

<body>
    <form id="datatble-form">
        <table>
            <tr>
                <td>Friend Name</td>
                <td><input name="FriendName" type="text" /></td>
            </tr>
            <tr>
                <td>Friend Age</td>
                <td><input name="FriendAge" type="text" /></td>
            </tr>
            <tr>
                <td>Position</td>
                <td><input name="Friendposition" type="text" /></td>
            </tr>
            <tr>
                <td>Office</td>
                <td><input name="Friendoffice" type="text" /></td>
            </tr>
        </table>

        <input id="submitdata" type="button" value="Submit" />
    </form>
</body>
</html>

My controller is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using datatableViewTocontroller.Models;

namespace datatableViewTocontroller.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult getData(string model)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            MyClass myClass = jss.Deserialize<MyClass>(model);
            return RedirectToAction("index");
        }

}

}

and My Model is :

namespace datatableViewTocontroller.Models
{
    public class MyClass
    {
        public string FriendName { get; set; }
        public string FriendAge { get; set; }
        public string Friendposition { get; set; }
        public string Friendoffice { get; set; }  
    }
}

Ok now I ellaborate my problem.
I have a form with the inputs for name, age, position and office and Iam trying to submit the data to the controller by serialize(). The form is getting serialized ( because it is displaying the values in the alert ) and controller call is also successfull like :

You can see that controller parameters are getting received

but while deserialzing I have got this error :
Invalid JSON primitive: FriendName.
like this :
Error while Deserializing the values into the model

How can I resolve this issue ? please help..

2

Answers


  1. Whatever you are getting in your action method of controller is not json data that’s why you are getting the error while deserializing it.

    Solution

    You can update your getdata method instead of passing string in parameter you can pass your model class which will bind data automatically and you will no longer required deserializing the json.

    [HttpPost]
    public ActionResult getData(MyClass model)
    {
      // Do whatever you want with model
      return RedirectToAction("index");
    }

    And also change your click method as below

    $("#submitdata").click(function () {
    	$.post("/Home/getData",$("#datatble-form").serialize()).done(function(data){
    		 alert('success');
    	}).catch(function(){
    		alert('failure');
    	});
    });
    Login or Signup to reply.
  2. 1.Add serializeObject function to serialize form data to json

    <script>    
            (function ($) {
                $.fn.serializeObject = function () {
    
                    var self = this,
                        json = {},
                        push_counters = {},
                        patterns = {
                            "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:[(?:d*|[a-zA-Z0-9_]+)])*$/,
                            "key": /[a-zA-Z0-9_]+|(?=[])/g,
                            "push": /^$/,
                            "fixed": /^d+$/,
                            "named": /^[a-zA-Z0-9_]+$/
                        };
    
    
                    this.build = function (base, key, value) {
                        base[key] = value;
                        return base;
                    };
    
                    this.push_counter = function (key) {
                        if (push_counters[key] === undefined) {
                            push_counters[key] = 0;
                        }
                        return push_counters[key]++;
                    };
    
                    $.each($(this).serializeArray(), function () {
    
                        // Skip invalid keys
                        if (!patterns.validate.test(this.name)) {
                            return;
                        }
    
                        var k,
                            keys = this.name.match(patterns.key),
                            merge = this.value,
                            reverse_key = this.name;
    
                        while ((k = keys.pop()) !== undefined) {
    
                            // Adjust reverse_key
                            reverse_key = reverse_key.replace(new RegExp("\[" + k + "\]$"), '');
    
                            // Push
                            if (k.match(patterns.push)) {
                                merge = self.build([], self.push_counter(reverse_key), merge);
                            }
    
                            // Fixed
                            else if (k.match(patterns.fixed)) {
                                merge = self.build([], k, merge);
                            }
    
                            // Named
                            else if (k.match(patterns.named)) {
                                merge = self.build({}, k, merge);
                            }
                        }
    
                        json = $.extend(true, json, merge);
                    });
    
                    return json;
                };
            })(jQuery);
        </script>
            <script>
                $(document).ready(function () {
                    $("#contenttable").DataTable({
    
                    });
    
                    $("#submitdata").click(function () {
    
                        var datatabledata = $("#datatble-form").serializeObject();
                        $.ajax({
                            url: "/Home/getData",
                            type: "POST",
                            dataType: "json",
                            data: { model: datatabledata },
                            crossDomain: true,
                            success: function (result) {
                                if (result.success == true) {
                                    window.location = result.redirecturl;
                                }
                            },
                            error: function () {
                                alert('failure');
                            }
                        });
                    });
                });
            </script>
    

    2. No need to deserialize MyClass in action codes,

    public IActionResult Index(MyClass model)
            {
                return View(model);
            }
    
            [HttpPost]
            public ActionResult getData(MyClass model)
            {
                //no need to deserialize MyClass
                return Json(new { success = true, redirecturl = Url.Action("Index", "Home", model) });
            }
    

    Screenshots of test:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search