How do I call a POST method from a partial view to an API controller in C#?

👉API Controller 

Ensure your API controller is decorated with [ApiController] and the action method handles [HttpPost] requests.  

[Route("api/[controller]")]
[ApiController]
public class DocumentsController : ControllerBase
{
    [HttpPost("DownloadZipFile")]
    public IActionResult DownloadZipFile([FromBody] TemplateFileModel model)
    {
        if (model == null || string.IsNullOrWhiteSpace(model.FilePath))
        {
            return BadRequest(new
            {
                status = false,
                message = "Invalid file path"
            });
        }

        // TODO: Add logic to generate or locate the ZIP file

        return Ok(new
        {
            status = true,
            message = "Success"
        });
    }
}

Partial View (_MyPartial.cshtml)

This partial view contains a button and a JavaScript function that triggers the API call.

<button type="button" onclick="downloadZipFile('/path/to/file.zip')">
    Download Zip
</button>

<script>
    function downloadZipFile(filePath) {
        var model = {
            FilePath: filePath
        };

        $.ajax({
            url: '/api/Documents/DownloadZipFile',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (response) {
                if (response.status) {
                    console.log("Success:", response.message);
                } else {
                    alert("File not found: " + response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error("An error occurred:", error);
            }
        });
    }
</script>

Key Improvements Made

  • Consistent method and function naming (downloadZipFile)
  • Proper spacing and indentation
  • Added charset=utf-8 for safer JSON handling
  • Used string.IsNullOrWhiteSpace() instead of IsNullOrEmpty()
  • Clear section headings for readability

How do I create a temporary DataTable and merge it into a DataSet in C#?

using System;
using System.Data;

public class Program {
    public static void Main() {
        // 1. Create a Master DataSet
        DataSet masterDataSet = new DataSet("BusinessDataSet");
        
        // 2. Create a Temporary DataTable
        DataTable tempTable = new DataTable("TempEmployees");
        
        // Define columns for the temp table
        tempTable.Columns.Add("ID", typeof(int));
        tempTable.Columns.Add("Name", typeof(string));
        tempTable.Columns.Add("Role", typeof(string));
        
        // 3. Add sample data to the temporary table
        tempTable.Rows.Add(1, "Alice", "Developer");
        tempTable.Rows.Add(2, "Bob", "Architect");
        
        Console.WriteLine("Temporary Table created with " + tempTable.Rows.Count + " rows.");
        
        // 4. Merge the DataTable into the DataSet
        // The Merge method combines the schema and data
        masterDataSet.Merge(tempTable);
        
        // 5. Verify the results
        Console.WriteLine("\nDataSet now contains table: " + masterDataSet.Tables[0].TableName);
        
        foreach (DataRow row in masterDataSet.Tables["TempEmployees"].Rows) {
            Console.WriteLine($"ID: {row["ID"]} | Name: {row["Name"]} | Role: {row["Role"]}");
        }
    }
}