Muneer
Muneer

Reputation: 7564

How to solve action argument type mismatch?

I have an action in my controller as follows.

    //
    // GET: /HostingAgr/Details/1
    public ActionResult Details(int id)
    {
        HostingAgreement hosting = hmEntity.HostingAgreements.SingleOrDefault(h => h.AgreementId == id);
        if (hosting == null)
        {
            TempData["ErrorMessage"] = "Invalid Agreement ID";
            return RedirectToAction("Index");
        }

        return View(hosting);
    }

Now if I call URL like below.. (for testing purpose)

/HostingAgr/Details/1fakeid

System will throw an Exception.

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'HostingManager.Controllers.HostingAgrController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

Because the id become string in URL parameter. How can I handle this situation without throwing an error by the system?

Upvotes: 0

Views: 1007

Answers (1)

jgauffin
jgauffin

Reputation: 101150

Accept a string and try to convert it:

public ActionResult Details(string id)
{
    var numericId;
    if (!int.TryParse(id, out numericId))
    {
        // handle invalid ids here
    }

    HostingAgreement hosting = hmEntity.HostingAgreements.SingleOrDefault(h => h.AgreementId == numericId);
    if (hosting == null)
    {
        TempData["ErrorMessage"] = "Invalid Agreement ID";
        return RedirectToAction("Index");
    }

    return View(hosting);
}

I would not recommend you to do so. Invalid ids should be treated as invalid ids. You are hiding errors otherwise. It might work today, but it will lead to a maintenance mess in the future.

Update

Anything changing 1fakeid into 1 is a workaround. It's a bad practise doing so. You users should be forced to enter proper ids.

You can turn on customErrors in web.config to hide exception details.

If you still want to proceed I think that you can solve the problem by adding a custom ValueProviderFactory.

Upvotes: 1

Related Questions