Calling function from Controller in cshtml file.

Aaron soggi 246 Reputation points
2022-05-10T22:07:57.18+00:00

Hello What i would like to do is call my GetCity method in my controller class once the user has submitted an input in the index.cshtml file.

Controller code:

  public async Task<ActionResult> GetCity(string name)   
        {  
            _logger.LogInformation("Get City request has been receieved");  
  
            try  
            {  
                var city = await _iclientConnectionHandler.GetCityData(name);  
                return View(city);  
  
            }  
            catch (Exception e)  
            {  
                _logger.LogInformation($"Error has occured when attempting to get city data {e.Message}");  
                return View(new { e.Message });                          
            };              
        }  

index.cshtml code:

@{  
    ViewData["Title"] = "Home Page";  
}  
  
<div class="text-center">  
    <h1 class="display-4">OpenAQ Application</h1>  
    <form method="get" class="cityInput">   
        <label for="fname">Enter a City:</label>  
        <input type="text" id="fname" placeholder="Type here" name="cname">          
        <input type="submit" value="Submit">              
    </form>     
</div>  

Could someone tell me how i would be able to do this? Thanks

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,156 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,230 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,366 Reputation points
    2022-05-10T22:47:51.333+00:00

    have the form submit to the getcity action, and have the text field name match the get city parameter name.

        <form method="get" class="cityInput" asp-controller="home" asp-action="GetCity"> 
             <label for="fname">Enter a City:</label>
             <input type="text" id="fname" placeholder="Type here" name="name">        
             <input type="submit" value="Submit">            
         </form>   
    
    0 comments No comments

  2. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-05-11T05:50:27.947+00:00

    Hi @Aaron soggi ,

    First, as Bruce said, when transfer data from view to the controller uses the form, the element's name and the parameter name should be matched. And, since you will submit the form from the Index page, there should be have a Index action method.

    Second, whether you are using the GetCity view (assume there has this view) to display the city list or use the Index page?

    If you are using a GetCity.cshtml page to display the city list, it is okey.

    But, if you are using the Index view page to display the city list (filter result), in the GetCity action method, you should also specify views when return data to view. Code like this:

    Controller:

    public class airQualityController : Controller  
    {  
        public async Task<IActionResult> Index(string cname)  
        {  
            var cities = await InnerGetCityAsync(cname);  
            return View(cities.results);  
        }  
        public async Task<ActionResult> GetCity(string cname)  
        {    
            try  
            {  
                var cities = await InnerGetCityAsync(cname);  
                return View("Views/airQuality/Index.cshtml", cities.results);  
    
            }  
            catch (Exception e)  
            {   
                return View(new { e.Message });  
            };  
        }  
    
        private async Task<RootModel> InnerGetCityAsync(string cname)  
        {  
            var client = new HttpClient();  
            client.BaseAddress = new Uri("https://docs.openaq.org/");  
            var results = new RootModel();  
            if (string.IsNullOrEmpty(cname))  
            {  
                results = await client.GetFromJsonAsync<RootModel>($"v2/cities").ConfigureAwait(false);  
            }  
            else  
            {  
                results = await client.GetFromJsonAsync<RootModel>($"v2/cities?city={cname}").ConfigureAwait(false);  
            }  
            return results;  
        }  
    }  
    

    Index.cshtml: Note: the controller name: airQuality; Action name: GetCity; Input element name: cname; GetCity action parameter name: cname

    @model IEnumerable<WebApplication2.Data.City>  
      
    @{  
        ViewData["Title"] = "airQuality Index";  
    }  
      
    <h1>IndexAsync</h1>  
     <div class="text-center">  
         <h1 class="display-4">OpenAQ Application</h1>  
         <form method="get" class="cityInput" asp-controller="airQuality" asp-action="GetCity">   
             <label for="fname">Enter a City:</label>  
             <input type="text" id="fname" placeholder="Type here" name="cname">          
             <input type="submit" value="Submit">              
         </form>     
     </div>  
    <p>  
        <a asp-action="Create">Create New</a>  
    </p>  
    <table class="table">  
             ... use a table to display the page model.  
    </table>  
    

    The result like this:

    200817-1.gif

    In the above sample code, if you change the form tag (<form method="get" class="cityInput" asp-controller="airQuality" asp-action="GetCity">) to <form method="get" class="cityInput">, it will submit the form to the index action, and the result like this:

    200808-2.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments