The following action does not require a querystring, but it does require the Id to be passed in the URL.
public ViewResult Details(int id)
{
Domain domain = db.Domains.Find(id);
return View(domain);
}
How do I change this so the name can be passed in the URL instead of the Id?
When I change that to the following, it produces an error “Sequence contains no elements” regardless of how I attempt to execute it.
public ViewResult Details(String name)
{
Domain domain = db.Domains.Where(d => d.Name == name).First();
return View(domain);
}
Any help is greatly appreciated.
“Sequence contains no elements” error is because your LINQ query is not returning any results for this where clause but you are trying to Apply the
First()function on the result set (which is not available for your where condition in this case).Use the First() function when you are sure that there is Atleast one element available in the resultset you are applying this function on. If there are no elements as the result of your LINQ expression, Applying
Firstwill throw the above error.For the URL to have the
nameparameter instead of the integer id, just change the parameter type tostring. Keep the variable name as id itself. because that is what the MVC Routing will use to help you write those pretty URLS.So now your URL can be like
Where
someNameis going to be the parameter value of yourDetailsaction method.I would use the
FirstOrDefaultand do a checking to see whether an element is available for the LINQ expression.FirstOrDefault will returns the first element of a sequence, or a default value if the sequence contains no elements.