简体   繁体   中英

Calling a controller function from onchange event in html view

I'm a new c# developer and I have a dropdownlist populated with string dates formatted like this: "Jul 2017". There can be as many as 12 entries in the list.

When a user selects a date, I want to pass that selection to a controller method, convert it to a DateTime format and then use that date for further processing.

How do I pass the user selection to the controller so it can be converted and used? I've included commented out code below to show how I want to do the conversion. Getting the date to the controller is my challenge.

I've looked at similar questions on this site and they all seem overly complex (perhaps due to my naivete), but I was hoping for a more streamlined solution.

Html View Code

@Html.DropDownList("selectList", Model.ReverseMonthsLists())

View Model Code

public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem 
                { Selected = index == 0, Text = dateString, Value = dateString })
            .ToList();
        return selectListItems;
    }

public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;
    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + 
        currentDate.Month - startDate.Month;
    var dates = new List<DateTime>(numberOfMonthsToShow);
    currentDate = currentDate.AddMonths(-1);

    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }

    return dates;
}

Controller function

    public ActionResult Report_Performance()
    {
        //var newDate = DateTime.Parse(strDate);  //<- Use newDate as parameter value into aVar to replace date at the end of the string
        var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, DateTime.Now.Date.AddMonths(-1));
        return this.View(aVar);
    }

The normal way to get a value to a controller is for the user to post the page back to the server, eg via a submit button. When this happens, the controller's action method can receive the selected item as an argument and then do what it needs to do. So if you just want the user to submit the form, and allow the web site to render the next page based on the selected value (and a list that you compute based on that value), that is all you need to do.

On the other hand, perhaps you don't want the user to submit the page; you want a series of dates to be displayed within the page, or for the dates to be processed by code running in the browser. If that is the case, I would suggest you perform the computations in Javascript within the browser itself, thereby avoiding the need for a round trip. Nothing in your GetDates() method requires any server side data, so it's just a question of converting your c# code to Javascript code.

In some rare cases, you will want a UX element on the page to get updated immediately based on a server computation, without the page being posted. If that is what you want, you'll have to use the AJAX solutions the other posters have provided. It's much more complicated and much more work. If you don't need that, use one of the solutions I provided above.

您可以对HTML Select选项(DropDownList)使用OnChange EventHandler来启动对控制器的Ajax调用,只需创建一个JavaScript函数即可对包含用户所选数据的Jquery Ajax请求执行到控制器的操作,并使用Return Json()而不是Return View() ,然后使用JavaScript处理检索到的数据,您的控制器将需要接受一个参数,以便从Ajax请求中接收数据

function SendDataToController (TheDropDownName){
       var DataToSend = $('#'+TheDropDownName).text();
       // Or Pass `this` From The Html When Assigning The Event Listener 
       // and Do Something Like var DataToSend = this.text();
        $.ajax({
          url: "@(Url.Action("ActionName", "ControllerName"))",
          data: DataToSend,
          success: function(ResponseFromController){
            //Do Stuff With Response 
          }
    });
}

This Will Send The Data To Controller So You Should Receive It in A Parameter

public ActionResult MyAction (string DataToSend)
{
  //Do Stuff With Data and Get a Json Object To Return 
   Return Json(JsonObject);
}

MVC Ajax Is Essential So You Should Learn It Before Tryin To Work On Any MVC Project, Also You Should Handle Request Error Using fail attr in The Ajax Setting But I Will Leave That To You

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM