How do I send a string through html into a controller. ASP.NET MVC

别来无恙 提交于 2020-04-18 05:35:53

问题


I have a method that exports data into Excel called ExportCSV().

I would like a method that has some added ability: ExportCSV(string searchString) where the string that's in the search bar on the web page is sent to this method where I can then use it. So my question is, how can I send the string in the search bar into this method?

The relevant code is below.

the html The 's are for a search function that does work, but I can't get a similar functionality to work for exporting


<input type="text" placeholder="Chem Name" name="cheminventory2String" value="@ViewData["Search"]" id="SearchString" />
<input type="submit" value="Search" class="btn btn-default" />

<a class="btn btn-default" asp-action="ExportCSV">Export Table</a>


here is the controller


public FileContentResult ExportCSV(string searchString)
{
     var dataTable = from m in _context.ChemInventory2.Include(c => c.Chemical).Include(c => Location).Include(c => c.Order)
                     select m;

     *code for making and filling the csv to export*

     return File(export.ExportToBytes(), "text/csv", "Chemical Inventory.csv");
}

The ExportCSV() works, but it exports everything in the table. I want it to only export what has been searched for. In the things that I've tried, nothing is every passed into the method. searchString is always empty.


回答1:


<form method="GET" asp-action="ExportCSV">    
    <input type="text" placeholder="Chem Name" name="cheminventory2String" value="@ViewData["Search"]" id="SearchString" />
    <input type="submit" value="Search" class="btn btn-default" />

    <button type="submit" class="btn btn-default">Export Table</a>
</form>

The name attribute on your HTML tag above needs to match the parameter your MVC ActionResult is taking, and since you were using an Anchor tag you were simply navigating people to your URL, without any parameters.

It should be wrapped inside of a form tag and then the anchor link should be replaced with a submit button.

You can then use your searchstring like below:

public FileContentResult ExportCSV(string cheminventory2String)
    {
         var dataTable = from m in _context.ChemInventory2.Include(c => c.Chemical).Include(c => Location).Include(c => c.Order)
                         where cheminventory2String == m.Chemical.Name select m;

         return File(export.ExportToBytes(), "text/csv", "Chemical Inventory.csv");
    }


来源:https://stackoverflow.com/questions/60979674/how-do-i-send-a-string-through-html-into-a-controller-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!