I am writing my first MVC app. While creating link for opening details view, I have to pass id.
In Controller method like as below:
public ActionResult getDetails(int UserMasetrId)
{
...Some Code
}
In VIEW link was generated as below:
<a title="View Details" href="@Url.Action("getDetails", "UserMaster", new {id=item.UserMasterId})"></a>
For above code link is generating as ...controllername/getDetails/13616
. But it throws error:
"The parameters dictionary contains a null entry for parameter 'UserMasterId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult getDetails(Int32)' in 'APP.Controllers.UserMasterController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
Now if I change action link as below?
<a title="View Details" href="@Url.Action("getDetails", "UserMaster", new {UserMasterId=item.UserMasterId})"></a>
It works fine but link change to ...controllername/getDetails?UserMasterId=13616
So please suggest any solution for parameter name as I write in action method and i want format of url not to show parameter name means the format of url should conrtoller/actionmethod/parametervalue
.
CodePudding user response:
The parameter name in your function should match the query parameter in your button link.
<a title="View Details" href="@Url.Action("getDetails", "UserMaster", new { UserMasterId = item.UserMasterId})"></a>
You should also declare a Route if you're not using the default Id
parameter.
[Route("ControllerName/getDetails/{UserMasterId}")]
public ActionResult getDetails(int? UserMasterId)
{
if (id == null)
{
return NotFound();
}
}
CodePudding user response:
What you are using is not ActionLink
. You are generating a link for you href
action only. You can generate a proper a
tag using the HtmlHelper: Html.ActionLink
like this:
Html.ActionLink("", "getDetails", "UserMaster", new { item.UserMasterId }, null)
This will generate anchor tag like this assuming item.UserMasterId
is 1:
<a href="/UserMaster/getDetails/1"></a>
And change your Controller
method to:
public ActionResult getDetails(int? id)
{
...Some Code
}