pucek7
pucek7

Reputation: 31

Sending a phrase (variable) from searcher (from view) to controller, asp.net mvc

I'm trying to create searcher in asp.net. I'm so green about it. I'm trying to create in view and send to controller variable, which has text written in searcher. In that moment, I have smth like that --> My question is, where and how create and send variable and give her data written in searcher?

Layout

form class="navbar-form navbar-left" role="search">
            @using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
            {
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="Wpisz frazę...">
                </div>
                <button type="submit" class="btn btn-default">@Html.ActionLink("Szukaj", "Index", "Searcher")</button>
            }
        </form>

Controller

 public class SearcherController : ApplicationController
{
    [HttpGet]
    public ActionResult Index(string message)
    {
        ViewBag.phrase = message;
        getCurrentUser();
        return View();
    }

}

View

@{
ViewBag.Title = "Index";
 }

<h2>Index</h2>
<ul>
    <li>@ViewBag.message</li>
</ul>

Upvotes: 1

Views: 77

Answers (1)

Mathew Thompson
Mathew Thompson

Reputation: 56439

You're missing a key part of MVC -> the Model.

Let's create one first:

public class SearchModel
{
    public string Criteria { get; set; }
}

Then let's update your "Layout" view (don't know why you had a form in a form?):

@model SearchModel

        @using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
        {
            <div class="form-group">
                @Html.EditorFor(m => m.Criteria)
            </div>
            <button type="submit" class="btn btn-default">@Html.ActionLink("Szukaj", "Index", "Searcher")</button>
        }

Then your action that serves that view:

[HttpGet]
public ActionResult Index()
{
    return View(new SearchModel());
}

Then your post method would be:

[HttpPost]
public ActionResult Index(SearchModel model)
{
    ViewBag.phrase = model.Criteria;
    getCurrentUser();
    return View();
}

Upvotes: 3

Related Questions