saving data in core without model

Roger 26 Reputation points
2022-02-09T19:24:40.8+00:00

In the Get command I'm reading data from tables with unknown column names using an sql returning a datatable and can show it in a view using the datatable as a model but the post/submit does not return anything.
I can see the HttpContext
string id = HttpContext.Request.Form["Id[0]"];

How should I change to posting jquery-ajax call update for each line.

    //Get
    public async Task<IActionResult> Edit()
            {
                var conn = _context.Database.GetDbConnection();
                await conn.OpenAsync();
                var command = conn.CreateCommand();
                command.CommandText = "SELECT * FROM table4";
                var reader = await command.ExecuteReaderAsync();

                DataTable dt = new DataTable();
                dt.Load(reader);
                dt.PrimaryKey = new DataColumn[]
                     { dt.Columns["id"],dt.Columns["idd"],dt.Columns["idf"] };

                return View(dt);
            }

    //post
            public async Task<IActionResult> Edit(DataTable dt)
            { 
                string id = HttpContext.Request.Form["Id[0]"];
                foreach (string key in HttpContext.Request.Form.Keys)
                {
//psedocode
                    string x  = HttpContext.Request.Form[key];
                  await _context.Database.ExecuteSqlRawAsync(@"Update [table4] SET {0} = {1} WHERE Id = {2}", new object[] { "Cont_one", x,  });                 

                }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,682 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 68,306 Reputation points
    2022-02-09T21:57:01.007+00:00

    while you can use any object as the view model passed to a view, the post back model must support serialization via json, or binding via the form post fields. A DataTable can be used for form post view model.

    change edit to:

    public IActionResult edit(IFormCollection form)

    in the view, you need to render the table data with form field with a name. say:

    <form>
    <table>
    @for (var i=0; i < Model.Rows.Count; ++i)
    {
         var row = Model.Rows[i];
        <tr>
        @foreach(var c in Model.Columns)
        {
              <td>
                     <input type="text" 
                           name="@$"{c.ColumnName}[{i}]""
                           value="@row[c]" />
              </td>
        }
        </tr>
     }
    <tr><td><button type="submit>Post</button></td></tr>
    </form>
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.