简体   繁体   中英

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>

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM