I want to access both /Blog and /Blog/1 where "1" is the ID of the Blog. Here is my code:
'
' GET: /Blog/
Function Index() As ViewResult
Return (View(db.Blogs.ToList()))
End Function
'
' GET: /Blog/(Integer)
Function Index(id As Integer) As ViewResult
Dim blog As Blog = db.Blogs.Find(id)
Return View("Details", "_MyLayout", blog)
End Function
It gives the error:
Server Error in '/' Application.
The current request for action 'Index' on controller type 'BlogController' is ambiguous between the following action methods: System.Web.Mvc.ViewResult Index() on type GemcoBlog.GemcoBlog.BlogController System.Web.Mvc.ViewResult Index(Int32) on type GemcoBlog.GemcoBlog.BlogController
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Reflection.AmbiguousMatchException: The current request for action 'Index' on controller type 'BlogController' is ambiguous between the following action methods: System.Web.Mvc.ViewResult Index() on type GemcoBlog.GemcoBlog.BlogController System.Web.Mvc.ViewResult Index(Int32) on type GemcoBlog.GemcoBlog.BlogController
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
How can I overload the Index() method?
Edit:
I am also trying to combine them like so:
'
' GET: /Blog/
Function Index(id As Integer) As ViewResult
If (id) Then
Dim blog As Blog = db.Blogs.Find(id)
'Return View(blog)
Return View("Details", "_MyLayout", blog)
Else
Return (View(db.Blogs.ToList()))
End If
'Return View(db.Blogs.Where(Function(x) x.Name = "Test").ToList())
End Function
However, the error I get is:
Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult Index(Int32)' in 'Blog.Blog.BlogController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult Index(Int32)' in 'Blog.Blog.BlogController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.