Home > other >  ASP.NET MVC - Ajax passing null value to controller
ASP.NET MVC - Ajax passing null value to controller

Time:05-17

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 >
    <label for="tableName" >Table Name</label>
    <input type="text"  id="tableName" aria-describedby="tableName">
  </div>

<form>
  <div >
    <label for="columnName" >Name</label>
    <input type="text"  id="columnName" aria-describedby="columnName">
  </div>
  <div >
        <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 >
    <input type="checkbox"  id="primaryCheck">
    <label  for="exampleCheck1">Primary key</label>
  </div>
  
</form>

<button id="addColumn" type="submit" >Submit</button>




<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" >Save</button>

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

just for sending the table use this

data: JSON.stringify(Table)
  • Related