3

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
  • 1
    What is Types in your Column.cs? Could you share your code about Types? Commented May 17, 2022 at 10:40
  • 1
    It's enum: public enum Types { Integer, Float, Double, String, Char, Boolean, Date } Commented May 17, 2022 at 10:43
  • Could you share more about your view? Commented May 17, 2022 at 10:46
  • 1
    I added to post you can see view end of post. Commented May 17, 2022 at 10:53

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

@HeadEx Could you tell me the version of the asp.net you use?
it's asp.net 5.0
@HeadEx You are welcome:) asp.net 5.0 is name asp.net core, Could you add your tag a "asp.net core" ?
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();
}

2 Comments

I tried both options but it still doesn't work.
Try again after to change Types property to int (inside of the Columns class). If you couldn't get still, that means there is another problem
0

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)

3 Comments

I tried but it still doesn't work
I think also you need to change button type from type="submit" to type="button", since it is an ajax call and type type="submit" will send the whole page to server.
or you can wrap the ajax call inside $("#Your Form ID Here").submit(function(event) {// Your ajax here } and remove onclick event inside $(document).ready
0

just for sending the table use this

data: JSON.stringify(Table)

1 Comment

it didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.