0

I am trying to call a controller method when the user clicks a button, I also need a variable passed to this method. This is the code I have.

View:

 <input type="number" id="nbrMetric" name=metricNbr class="form-control" style="width:75px;" min="0">

@Html.ActionLink("Search", "InputTest", "CustomersController", new { @class = "btn btn-info", @Metric = "nbrMetric" })

Controller:

    public ActionResult InputTest(int Metric)
            {
               //Do Something

                return View();
            }
1
  • 1
    It probably should be Customers instead of CustomersController. Commented May 23, 2016 at 13:43

3 Answers 3

5

This creates a button that when clicked will redirect to a controller/Action (Dashboard/Index)

<button type="button" class="btn btn-default active" onclick="location.href='@Url.Action("Index", "Financial")'">Financial</button>

This adds the ability to send a parameter with the request:

<button type="button" class="btn btn-default active" onclick="location.href='@Url.Action("Financial", "KsDashboard", new { id = 257 }))'">Financial</button>

here is the html produced :

<button class="btn btn-default" onclick="location.href='/KsDashboard/Financial/123'" type="button">Financial</button>

Basically all you are doing is embedding an @Url.Action into the button's onclick event where the @Url.Action simply returns the Url to the controlleryou wish to redirect to

MS Documention for @Url.action:

Sign up to request clarification or add additional context in comments.

Comments

3

you must send back a form the source code like this: Model/Yourmodel.cs:

 public class FooModel
    {
        public int Metric { get; set; }
    }

Your controller:

public ViewResult InputTest() {

    return View();
}

[HttpPost]
public ActionResult SubmitInputTest(FooModel model) { 
    //your code 
    //do stuff

    return RedirectToAction("index");
}

Your page:

    @model MVCWebApp.Models.FooModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>InputTest</title>
</head>
<body>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>


    @using (Html.BeginForm("SubmitInputTest","Home", FormMethod.Post))
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>FooModel</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Metric, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Metric, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Metric, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

4 Comments

you may use ajax tecnologies
While your answer is correct, I don't see a reason for using a form and a POST request for this given scenario where a simple link with a querystring parameter would be sufficient, unless of course there's a need to support a non-JS version of the page in which case a form would be necessary.
because i suppose that he need to get a value by input text
sure I got that part, but a) a form can have a GET action or b) the input value can be appended to a link using javascipt. Again, I'm not saying a form post is wrong, just that a GET request feels more appropriate.
1

You can see in the duplicate question that I've put in the comments the full explanation, in your case this should work:

@Html.ActionLink("Search", "InputTest", "Customers", new { Metric = 3 }, new { @class = "btn btn-info" })

It's actually this overload of Html.ActionLink:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    RouteValueDictionary routeValues,
    IDictionary<string, Object> htmlAttributes
)

https://msdn.microsoft.com/en-us/library/dd493068(v=vs.108).aspx

2 Comments

I tried using this code but I seem to be getting this error every time "The parameters dictionary contains a null entry for parameter 'Metric' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult InputTest(Int32)' in 'FutatillDataAnalytics.Controllers.CustomersController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters", It seems it is not getting the value from the metric number input
I now understand what you are trying to do. Html.ActionLink is not suitable for posting parameters from an input to the controller, you should use a form with a submit button instead, something like C.Fasolin suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.