0

I checked couple of posts in SO and changed my code according to few suggestions still it is not working.

I am building an ASP.NET Core MVC application. When executed, the View presents a list of rows with ID. Each row has a corresponding button and it is required to pass the ID of the row whose button was clicked.

In the View, I have made call to a JS function as below:

            <tr>
                <td>
                    <input type="submit" id="btnSubmit" value="Update Status" class="ids" data-id="@sheet.ID" onClick="sendId(@sheet.ID)" />
                </td>
            </tr>

The JS function is as below:

    function sendId(id) {
        var rowId = parseInt(id);
        $.ajax({
            url: '/UpdateStatus/' + rowId,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            success: function() { alert('Success'); },
            error: function() { alert('Error'); }
       });
       }

The controller action method is hit when button is clicked but it also triggers the error function of the above javascript code and it passes null to the action method.

        [HttpPost]
        [Route("UpdateStatus/{id}")]
        public void UpdateStatus(string mID)
        {
            // Do something
        }

** Edited **

Posting complete controller code on demand.

   public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

     
        [Route("~/UpdateStatus/{id}")]
        public void UpdateStatus([FromQuery] string mID)
        {
            // Do Something
        }

        [HttpGet]
        [Route("Index")]
        public ActionResult Index()
        {
            //TemplateData template = new TemplateData();
            List<TemplateData> templateList = new List<TemplateData>();
            templateList = ImportExcel();
            return View(templateList.AsEnumerable());
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        private List<TemplateData> ImportExcel()
        {
            // Read Excel
            // path to your excel file
            string path = "C:\\ExcelData\\Results.xlsx";
            FileInfo fileInfo = new FileInfo(path);

            ExcelPackage package = new ExcelPackage(fileInfo);
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            ExcelWorksheet ws = package.Workbook.Worksheets["Data"];

            List<TemplateData> templateList = new List<TemplateData>();
 

            // get number of rows and columns in the sheet
            int rowCount = ws.Dimension.Rows; // 20
            int ColCount = ws.Dimension.Columns; // 7

            // loop through the worksheet rows and columns
            for (int row = 2; row <= rowCount; row++)
            {
                TemplateData template = new TemplateData();
                template.ID = ws.Cells[row, 1].Value.ToString();

                if (ws.Cells[row,6].Value != null)
                {
                    template.EmpName = ws.Cells[row, 6].Value.ToString();
                }

                if (ws.Cells[row, 7].Value != null)
                {
                    template.WareHouse= ws.Cells[row, 7].Value.ToString();
                }

                if (ws.Cells[row, 12].Value != null)
                {
                    template.Observation = ws.Cells[row, 12].Value.ToString();
                }

                templateList.Add(template);
            }

            return templateList;
        }

    }
2
  • You can print out the error information by using error: function( jqXHR, textStatus, errorThrown) { console.log(jqXHR.responseText);. You can also use the browsers debugging tools to check the response from the server. Right now, you haven't shown us what that error is, so we can't diagnose. Commented Jun 23, 2021 at 13:02
  • I see your controller function is returning void. This might be a problem as you're not sending anything back to the ajax. try sending back a 200 response if UpdateStatus worked properly and a 400 (bad request data) or 500 ( server encountered a problem writing to the database or something) response as appropriate if UpdateStatus didn't perform properly. Commented Jun 23, 2021 at 13:11

2 Answers 2

1

I don't know why you need ajax, but if you still want it you have to remove type="submit" from button

<td>
 <input id="btnSubmit" value="Update Status" class="ids" onClick="sendId(@sheet.ID)" />
</td>

fix your ajax


    $.ajax({
        url: '/UpdateStatus/' + id,
        type: 'GET',
       success: function() { alert('Success'); },
        error: function() { alert('Error'); }
   });

and remove Post from the action and fix the route

[Route("~/UpdateStatus/{id}")]
public IActionResult UpdateStatus(string id)
{
    // Do something
    return Ok();
}
Sign up to request clarification or add additional context in comments.

11 Comments

Still passing NULL
Can you post the whole controller pls?
Please check now.
@RKh Remove [FromQuery] pls. It is not in my answer
@RKh If you change everytning according to my answer, and your Id is not empty or null, you will get Id value in the action. You should never mix the answers
|
1

You need to change the name of the parameter to match the route, like so:

[HttpPost]
[Route("UpdateStatus/{id}")]
public void UpdateStatus(string id)
{
    // Do something
}

6 Comments

Tried. This too not working. BTW, I have added complete Controller code above.
@RKh You still need to fix the name of the parameter. You have id in the route and mID as the parameter variable name. They need to be the same.
Oh. Didn't know that. Let me try.
Thanks Thanks. It worked. But I cannot mark two answers as answers. The JS change of the other user also worked. Giving thumps up to you.
@RKh Looking at it again, the [FromQuery] shouldn't be necessary. So probably it was just the parameter name that was causing the issue. I've edited my answer to reflect that.
|

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.