Home > Software design >  Can I include the content of an input text box in a form post (Asp.Net Core)?
Can I include the content of an input text box in a form post (Asp.Net Core)?

Time:10-15

I have an Asp.Net Core MVC webapp that has an IEnumerable of objects that it displays on the screen as a column of buttons. I also have a search bar that I want to be able to filter the button based on whether they contain the search string.

I have it working so that I can manually change the url by appending ?searchString="Whatever" and it works correctly. But how can I make the form post contain the searchString value based on whatever is currently in the text box? I've tried variations of using the id of the input box but haven't been able to figure it out.

Here's basically what it looks like.

<form method="post" action="@Url.Action("Index", "Home", new { searchString = "What goes here?"})">
  <button  type="submit">Search</button>
  <input  type="text" placeholder="Enter Name">
</form>

Can I put something in the url.action that will capture the content of the text box and send it with the post? Or do I need to try another implementation?

CodePudding user response:

When submitting a form you can bind your form input so that it is able to be read by the controller. To do this at a minimum you need to add a name attribute to the input so that it looks like:

<input  type="text" name="search" placeholder="Enter Name">

Then, on the controller, you can add that value as a parameter like so:

public IActionResult Index( string? search = null )

You won't need to keep the searchString object in your Url.Action call either.

As your form grows, it would be better to eventually move to model-binding where you may have a ViewModel like:

public class SearchViewModel{
   public string Search { get; set;}
   public string OtherThing { get; set}
}

And then on your controller you would do:

public IActionResult Index( SearchViewModel viewModel )

And on your form you can use tag helpers:

@model SearchViewModel At the top of the page

<form method="post" action="@Url.Action("Index", "Home")">
  <button  type="submit">Search</button>
  <input  type="text" asp-for="Search" placeholder="Enter Name">
</form>
  • Related