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

0 Comments:

Post a Comment