user2884789
user2884789

Reputation: 533

ASP.NET MVC pass a parameter from a view to a controller

I'm looking for a way to know what link was pressed when a controller was called. My link is here in my view page:

<li id="tabFiles"><a href="~/Files" id="test">Files</a></li>

and my Files controller is here:

    public ActionResult Index(string submit)
    {
        string s = submit;

            return View();

    }

I tried to pass in a string hoping it would be the id of the clicked link, but this only returns a null.

Upvotes: 1

Views: 108

Answers (2)

Mehrzad Chehraz
Mehrzad Chehraz

Reputation: 5137

You should pass the id as query string:

<li id="tabFiles"><a href="~/Files/?id=test">Files</a></li>


public ActionResult Index(string id)
{
    string s = id;
    return View();
}

Or you may want to pass that in this form:

<li id="tabFiles"><a href="~/Files/test">Files</a></li>

The way you send parameters to the controller depends on how you have configured routing.

Upvotes: 3

TotPeRo
TotPeRo

Reputation: 6781

You can create custom action filter and set this on controller like this:

...
[CustomActionFilter]
public class FilesController : Controller
{
    ...
}

and on this custom filter you can get action name like this:

public class 

CustomActionFilter : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)


    {
        // TODO: Add your acction filter's tasks here

        // Log Action Filter Call
        MusicStoreEntities storeDB = new MusicStoreEntities();

        ActionLog log = new ActionLog()
        {
            Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
            Action = filterContext.ActionDescriptor.ActionName + " (Logged By: Custom 

Action Filter)",
            IP = filterContext.HttpContext.Request.UserHostAddress,
            DateTime = filterContext.HttpContext.Timestamp
        };

        storeDB.ActionLogs.Add(log);
        storeDB.SaveChanges();

        this.OnActionExecuting(filterContext);
    }
}

More details you can find here on Microsoft site or on this question.

Upvotes: 1

Related Questions