Passing multiple value from MVC3 View to an Action

2019-07-07 08:32发布

问题:

I wonder if anybody can help me here. I apologise for sounding like a thicko but I'm new to MVC3 and I'm trying to pass 2 values from a view to an action method but it just isn't playing fair!

HTML:

@Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager", 
new { htmlTokenId = item.Id }, new { htmlDataTemplateId = 1 })

ACTION METHOD:

public ActionResult AssignTokenToDataTemplate(int htmlTokenId, int htmlDataTemplateId)
{
    // Do some database stuff here
    return View("AssignAnExistingTokenToHtmlDataTemplate", new {templateId = htmlDataTemplateId});
}

I want to pass two integers into the AssignTokenToDataTemplate action method but I cannot get it to work?!

Can anybody see where I'm going wrong? :(

回答1:

You could pass both values using the routeValues parameter:

@Html.ActionLink(
    "ASSIGN",                             // linkText
    "AssignTokenToDataTemplate",          // actionName
    "HostHtmlTokenManager",               // controllerName
    new {                                 // routeValues
        htmlTokenId = item.Id, 
        htmlDataTemplateId = 1 
    }, 
    null                                  // htmlAttributes
)


回答2:

Try

@Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager", 
new { htmlTokenId = item.Id , htmlDataTemplateId = 1 })

However you might want to consider using a model (a type of your own) to pass them together as one.



回答3:

You have to include both parameters in the anonymous class:

@Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager", 
            null, new { htmlDataTemplateId = 1, htmlTokenId = item.Id })


回答4:

Try;

@Html.ActionLink("ASSIGN", "AssignTokenToDataTemplate", "HostHtmlTokenManager", 
new { htmlTokenId = item.Id, htmlDataTemplateId = 1 })

Matt