skip to Main Content

Do you know what to put at the asp-route-word, I am not able to find it. This is my code:

<form class="d-flex" method="get">
   <input class="form-control me-sm-2" type="search" placeholder="Search" id="searchWord" />
   <button class="btn btn-secondary my-2 my-sm-0" type="submit" asp-controller="Word" asp-action="Index" asp-route-word="???">
                        Rechercher
   </button> </form>

Here is the function in my controller:

public IActionResult Index(string? word)
    {
        if (word == null)
        {
            IEnumerable<Word> objWordList = _db.Words;
            return View(objWordList);
        }
        else
        {
            IEnumerable<Word> objWordList = _db.Words.ToArray().Where(w => word.StartsWith(w.NewWord));
            return View(objWordList);
        }
        
    }

So do you know how to get input text in order to pass it to my controller? I always get word null.
Thanks!

2

Answers


  1. You have to give the name and value property to your button:

    <button name="word" value="Rechercher" class="btn btn-secondary my-2 my-sm-0" type="submit" asp-controller="Word" asp-action="Index">
       Rechercher
    </button>
    

    And your Controller method will be the same.

    OR

    You can use Request.Form from the name tag to access the form variables:

    public IActionResult Index()
    {
    
        if (Request.Form["word"] == null)
        {
            IEnumerable<Word> objWordList = _db.Words;
            return View(objWordList);
        }
        else
        {
            IEnumerable<Word> objWordList = _db.Words.ToArray().Where(w => word.StartsWith(w.NewWord));
            return View(objWordList);
        }   
    }
    
    Login or Signup to reply.
  2. how to get input text in order to pass it to my controller

    You can use name attribute to bind the input text, try the code like below:

    <form class="d-flex" method="get" >
        <input name="word" class="form-control me-sm-2" type="search" placeholder="Search" id="searchWord" />
        <button  class="btn btn-secondary my-2 my-sm-0" type="submit" asp-controller="Word" asp-action="Index">
            Rechercher
        </button>
    </form>
    

    result:

    enter image description here

    what to put at the asp-route-word

    You can put in the <a ... ></a> tag, read asp-route-{value} to know more.

    Like:

    <a asp-controller="Word"
           asp-action="Index"
           asp-route-word="????">Send word</a>
    

    result:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search