Reputation: 29
I had a code that was working the past few weeks and am getting an ERROR "Input string was not in a correct format"
NB:(MVC Asp.net)
the view gets data from the Razor page URL and Execute a query
the URL is like this: https://localhost:44348/Devices/Details/5?typeName=Dongle
and the following the View code :
public ActionResult Details(string typeName, int? id)
{
var sql = "SELECT A.*," +
" COALESCE(ps.first_name, '') as firstname," +
" COALESCE(ps.last_name, '') as lastname," +
" COALESCE(p.program_name, '') as program_Name, " +
" COALESCE(l.loan_date, '') as loan_date, " +
" COALESCE(l.return_date, '') as return_date" +
" FROM devices A" +
" LEFT JOIN device_loans l on l.device_id = A.device_id" +
" LEFT JOIN persons ps on ps.person_id = l.person_id" +
" LEFT JOIN programs p on A.program_id = p.program_id" +
" WHERE A.device_type = '" + typeName + "' and p.program_id = "+ id +";";
var devices = _context.DeviceDetails
.FromSqlRaw(sql)
.ToList();
return View(devices);
}
I have tried Passing parameters with parameter placeholders but still not working
please help.
Upvotes: 0
Views: 227
Reputation: 144
Because your parameter id: is nullable, you need combine sql like:
var sql = "SELECT A.*," +
" COALESCE(ps.first_name, '') as firstname," +
" COALESCE(ps.last_name, '') as lastname," +
" COALESCE(p.program_name, '') as program_Name, " +
" COALESCE(l.loan_date, '') as loan_date, " +
" COALESCE(l.return_date, '') as return_date" +
" FROM devices A" +
" LEFT JOIN device_loans l on l.device_id = A.device_id" +
" LEFT JOIN persons ps on ps.person_id = l.person_id" +
" LEFT JOIN programs p on A.program_id = p.program_id" +
" WHERE A.device_type = '" + typeName + "'";
if(id!=null){
sql += " and p.program_id = "+ id +";";
}
BTW: your code has SQL injection risk
Upvotes: 1