0

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.

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

if you still want combine sql, you must replace single quot like : typeName = typeName.Replace("'", "''");

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.