12

I have a simple search form on my _Layout page.

How can I easily pass the value from search-fld to the controller? Without having to create a Model or ViewModel.

@using (Html.BeginForm("Search", "Home", new { id = "search-fld" }, FormMethod.Post, new { @class = "header-search pull-right" }))
{
    @Html.AntiForgeryToken()

    <input type="text" placeholder="Search" id="search-fld">
    <button type="submit">
        <i class="fa fa-search"></i>
    </button>
}

If I run this then "search-fld" get send to the controller (offcourse)

Use Ajax form instead and get the value with Jquery?

2 Answers 2

15

Simply by giving your input a name attribute:

<input type="text" placeholder="Search" id="search-fld" name="searchValue">

Then matching that name with a parameter in your controller HttpPost method:

[HttpPost]
public ActionResult Search(string searchValue)
Sign up to request clarification or add additional context in comments.

3 Comments

Yea, that kind of works. The only problem is that the URL now is localhost:52223 and if i search for "asd" it passes the parameter and the URL changes to localhost:52223/Search but I want it to say localhost:52223/Search/asd and this works if I have a Custom route on the controller like this: [Route("Search/{searchString}")] BUT then it doesn't work since it doesnt pass the value in route attributes from the form :/ Any suggestions?
Also have custom route mapped in Route.Config. Like this: routes.MapRoute( name: "Home", url: "{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
If the names match up it will, i.e. if you have public ActionResult Search(string searchValue), then you also need name="searchValue" on your input and [Route("Search/{searchValue}")] as your route.
0

You can use an Ajax call like that :

 $(document).ready(function() {
$("#yourButton").click(function () {
            var yourValue = $("#search-fld").val() ;
            var url = "Search/asd/";
            $.ajax({
                url: url,
                cache: false,
                type: 'POST',
                data: {
                    searchValue = yourValue
                }
                success: function (data) {
                    if (data === true) {
                        alert('Success');
                    } else {
                        alert('Failed');
                    }
                    }
                })
            })
        })

And Your Method in controller :

[HttpPost]
public ActionResult asd(string searchValue)
{

}

Comments

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.