Search code examples
c#model-view-controllerviewcontrollerwebgrid

Pass a WebGrid to Controller


I want to send the whole WebGrid to my controller and convert it into a DataTable.

var grid1 = new WebGrid(Model.dsvm as IEnumerable<ASP_Upload_Version_1.Models.Share_Template>, canPage: true, canSort: false);
@grid1.GetHtml(tableStyle: "table table-sm table-striped table-condensed",
htmlAttributes: new { @id = "GridPractice", @class = "table table-sm table-striped-left table-bordered table-condensed", @style = "width:100%" },
columns: grid1.Columns(
    grid1.Column("PracticeArea", "Practice Area"),
    grid1.Column("MarketArea", "Market Area"),
    grid1.Column(format: @<text>
    <a data-title="Are you sure to deactivate this Input?" class="Delete"><i class="fa fa-trash" style="color:red"></i></a></text>, header: "Remove")));

So, that I can send the datatable as a User defined type Parameter to a SQL Procedure.

Is converting the WebGrid into a JSON result a good approach? are there any easier alternatives?


Solution

  • I converted the Grid into json using

    var _griddata = gridTojson("GridPractice");
    

    and passed it to the controller. Over there I converted it into a dictionary using

    Dictionary<string, string[]> log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(GridData);
    

    Then I moved the data into a DataTable with the following code

    DataTable PracticeTable= new DataTable();
    
    PracticeTable.Columns.Add("TestColumn1");
    PracticeTable.Columns.Add("");
    
    for (int i = 0; i < log.Count; i++)
    {
        PracticeTable.Rows.Add(log["" + i + ""][0], log["" + i + ""][1]);
    }