0

I am new to the web side of things and I am currently struggling with Razor Pages. Can someone explain the ways I can get a value from control in this case.

How can I extract the content of the selected and pass it to a variable to the code behind;

@page
@model ViewToVM.Pages.IndexModel
@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>
<section id="cityList">
 <select id="selectedCity">
  @using Model;
  @foreach(City city in Model.Cities)
  {
   <option>@city.SelectedCity</option>
  }
 </select>
</section>

with this code behind

using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
using ViewToVM.Model;

namespace ViewToVM.Pages
{
    public class IndexModel : PageModel
    {
        public List<City> Cities = new List<City>()
        {
            new City("Sofia"),
            new City("Plovdiv"),
            new City("Velingrad")
        };
        public string selectedCities = string.Empty;

        public void OnGet()
        {

        }
    }
}

The City class just contains a single string for demo purposes. I know this is probably a pretty bad way to do the code behind but It help me illustrate the problem better.

EnvelopedDevil
  • 658
  • 1
  • 13
  • 29

2 Answers2

1

you can use Javascript/Jquery and add an onchange event listener that can make a Ajax call and pass it's value to the controller. similar to the code below:

<script type="text/javascript">
// assuming you're using jQuery
$("#selectedCity").change( function (event) {
    $.ajax({
        url: "Controller/PostDropdown/",
        data: { id = $(this).val() },
        type: "POST",
        dataType: "html",
        success: function (data, textStatus, XMLHttpRequest) {
             // do something 
        }
    });
});

max_dev
  • 81
  • 5
1

You should wrap select with form. When form was submitted, it will call your controller.

see this: Submitting form and pass data to controller method of type FileStreamResult

Steven Chou
  • 1,504
  • 2
  • 21
  • 43