ASP.NET Core中Get方法参数未传递至Action的问题
Let's troubleshoot why your pID parameter isn't making it to the Save GET action. Here are the most common fixes and checks to get this working:
1. Verify Your DataTables Link Generation
First, make sure the links generated by DataTables include the pID parameter correctly. If you're adding edit links in a DataTables column, your render function needs to explicitly append the parameter to the URL.
For example, if your test case data has an ID field, update your columns configuration like this:
var oTable = $('#myDatatable').DataTable({ "ajax": { "url": '/home/GetTestCases' }, "columns": [ // Other column definitions... { data: "ID", // Match this to the actual field name in your dataset render: function(data, type, row) { // Generate a link with pID appended as a query parameter return `<a href="/Home/Save?pID=${data}">Edit</a>`; } } ] });
- Double-check that the field name (e.g.,
ID) matches exactly what's returned from your/home/GetTestCasesendpoint. Use your browser's dev tools (F12 > Network tab) to inspect the AJAX response and confirm the field name.
2. Confirm Action Method Parameter Binding
Ensure your Save action is configured to accept the pID parameter correctly. While your current code works for query parameters, you can make it more robust by explicitly defining the route or adding a default value:
[HttpGet("Save/{pID?}")] // Optional route parameter for cleaner URLs like /Home/Save/123 public async Task<ActionResult> Save(string pID = null) { if (string.IsNullOrEmpty(pID)) return View(new TestCaseViewModel()); else return View(await m_TestCaseManager.FindByID(pID)); }
- This modification supports both query parameters (
/Home/Save?pID=123) and route parameters (/Home/Save/123), giving you flexibility. - Make sure the parameter name
pIDmatches exactly between the URL and the action method (ASP.NET is case-insensitive by default, but consistency avoids issues).
3. Validate the Generated URL
Use your browser's dev tools to inspect the rendered link:
- Right-click the edit link in your DataTable and select "Inspect".
- Check the
hrefattribute of the<a>tag. It should look like/Home/Save?pID=your-test-case-id. - If the parameter is missing or has an empty value, your
renderfunction isn't accessing the correct data from the row object. Try usingrow.YourActualIDFieldNameinstead ofdataif needed.
4. Debug the Action Method
Add a breakpoint in your Save action and run your application in debug mode:
- When you click the edit link, check if
pIDis null or has the expected value. - If it's null, the URL isn't passing the parameter correctly (go back to step 1/3). If it's populated, your issue might be elsewhere in the
FindByIDcall.
内容的提问来源于stack exchange,提问作者A.Mills

