skip to Main Content

I am trying to send data from view to controller with Ajax but data is coming to controller as null.I tried many things but couldn’t find a solution.frombody attribute didn’t fix the problem, I made a few changes in startup but they didn’t help me either.

Here are my scripts:

$(document).ready(function() {
    $("#addColumn").click(function() {
        AddColumnRecords();
    });
    $("#saveRecords").click(function() {
        SaveRecords();
    });
});

function AddColumnRecords() {
    var columnRecords="<tr><td>" + $("#columnName").val() + "</td><td>" + $("#type").val() +"</td><td>"+ document.getElementById('primaryCheck').checked+ "</td></tr>";
    $("#ColumnTable").last().append(columnRecords);
     $("#columnName").val(" ");
}

function SaveRecords() {
    var Columns = new Array();
     $("#ColumnTable").find("tr:gt(0)").each(function(){
        var name=$(this).find("td:eq(0)").text();
        var type=$(this).find("td:eq(1)").text();
        var isPrimary=$(this).find("td:eq(2)").text();
        var ColumnModel={};
        ColumnModel.Name = name;
        ColumnModel.Type = parseInt(type);
        ColumnModel.IsPrimaryKey = isPrimary;
        Columns.push(ColumnModel);
     });
    var Table={};
    var tableName=$("#tableName").val();
    Table.TableName=tableName;
    Table.Columns=Columns;
    console.log(JSON.stringify(Table));

    $.ajax({
        type:'POST',
        dataType:'JSON',
        contentType:'application/json; charset=utf-8',
        url:'/table/createtable',
        data:{table : JSON.stringify(Table)},
        success:function(data){alert("success")},
        error:function(){alert("error")}
    });
}

My table is:

public class Table
{
    public string TableName { get; set; }
    public List<Column> Columns { get; set; } = new List<Column>();
}

Column model class is:

public class Column
{
    public string Name { get; set; }
    public virtual Types Type { get; set; } = Types.String;
    public virtual bool IsPrimaryKey { get; set; } = false;
}

And this is the action method:

[HttpPost]
public IActionResult CreateTable([FromBody] Table table)
{
    return View();
}

console log

<div class="mb-3">
    <label for="tableName" class="form-label">Table Name</label>
    <input type="text" class="form-control" id="tableName" aria-describedby="tableName">
  </div>

<form>
  <div class="mb-3">
    <label for="columnName" class="form-label">Name</label>
    <input type="text" class="form-control" id="columnName" aria-describedby="columnName">
  </div>
  <div class="mb-3">
        <select class="form-select" aria-label="Default select example" id="type">
            @{
                <option value=3>@DatabaseSample.Models.Types.String</option>
                <option value=0>@DatabaseSample.Models.Types.Integer</option>
                <option value=5>@DatabaseSample.Models.Types.Boolean</option>
                <option value=4>@DatabaseSample.Models.Types.Char</option>
                <option value=2>@DatabaseSample.Models.Types.Double</option>
                <option value=1>@DatabaseSample.Models.Types.Float</option>
                <option value=6>@DatabaseSample.Models.Types.Date</option>
            }
</select>
  </div>

  <div class="mb-3 form-check">
    <input type="checkbox" class="form-check-input" id="primaryCheck">
    <label class="form-check-label" for="exampleCheck1">Primary key</label>
  </div>
  
</form>

<button id="addColumn" type="submit" class="btn btn-primary">Submit</button>




<table class="table" id="ColumnTable">
  <thead>
    <tr>
      <th scope="col">Column name</th>
      <th scope="col">Type</th>
      <th scope="col">Primary key</th>
    </tr>
  </thead>
</table>
<button id="saveRecords" type="submit" class="btn btn-primary">Save</button>

4

Answers


  1. remove [FromBody] and try this

    let Table = {
           TableName: $("#tableName").val(),
           ColumnsStr :JSON.stringify(Columns)
     //create a new property in Table model, calls ColumnsStr which will receive ColumnsStr 
    };
    
    $.ajax({
            type:'POST',
            dataType:'json',
            contentType:'application/json; charset=utf-8',
            url:'@(Url.Action("CreateTable", "table"))',
            data:Table,
            success:function(data){alert("success")},
            error:function(){alert("error")}
        });
    
    

    and in the controller you can do that:

    table.Columns = JsonSerializer.Deserialize<List<Column>>(table.ColumnsStr)
    
    Login or Signup to reply.
  2. In your ajax send codes, you convert the model to string!

    $.ajax({
        type:'POST',
        dataType:'JSON',
        contentType:'application/json; charset=utf-8',
        url:'/table/createtable',
        data:{table : JSON.stringify(Table)},  //  <<------------- HERE
        success:function(data){alert("success")},
        error:function(){alert("error")}
    });
    

    that’s mean you send a model like this; { table: "..."}

    But your controller wants a Table model.

    First option for solution; dont convert to string by JSON.stringfy()

    $.ajax({
        type:'POST',
        dataType:'JSON',
        contentType:'application/json; charset=utf-8',
        url:'/table/createtable',
        data: Table,  //  <<------------- HERE
        success:function(data){alert("success")},
        error:function(){alert("error")}
    });
    

    Or second option; change controller paramter from Table to string. When you get the model string, then convert it to Table model inside of the controller function.

    [HttpPost]
    public IActionResult CreateTable([FromBody] string table)
    {
        var mTable =  new JavaScriptSerializer().Deserialize<Table>(table);
        return View();
    }
    
    Login or Signup to reply.
  3. just for sending the table use this

    data: JSON.stringify(Table)
    
    Login or Signup to reply.
  4. Below is a work demo, you can refer to it.

    Change ajax like below:

        ...
        var Table={};
        var tableName=$("#tableName").val();
        Table.TableName=tableName;
        Table.Columns=Columns;
        console.log(JSON.stringify(Table));
      
    
          $.ajax({
                    url:'/Home/Createtable',  
                    type:'POST',                   
                    data:Table,
                    success:function(data){alert("success")},
                    error:function(){alert("error")}               
                });
    

    In HomeController:

           public IActionResult Index()
            {
                return View();
            }
           [HttpPost]
            public JsonResult CreateTable(Table table, List<Column> Columns)
            {
                var ccc = 0;  // do your staff...
                return Json(ccc);
            }
    

    Result:

    enter image description here

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