Pass list of strings from controller to view

Santosh Umarani 81 Reputation points
2022-01-26T14:09:22.663+00:00

Hi,

I want to send a list of items when a new item in dropdown is selected. This is the controller class:

public List<string> GetVersionNumber()
{ return allowedList;
}

This is the view:

        $('#testTypeName').change(function() {
            $.ajax({
                type: "POST",
                url: "/TestCases/GetVersionNumber",
                data: { "testTypeName": $('#testTypeName').val() },
                dataType: "json",
                success: function(data) {
                    $("#testTypeName").selectedItem = data;
                }
            });
        });

My first question is should I use ActionResult in controller ? If yes, how can I use?
OR I can use a method which will result list of strings? If yes, how can I use ?
Kindly waiting for your response.

Thanks,
Santosh

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,235 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 47,461 Reputation points
    2022-01-26T15:20:31.243+00:00

    Depends upon the type of controller you have really. If you are building a web API controller (deriving from ApiController) then the return type is fine. You only need to use ActionResult if you need to return a mix of return types (such as data, not found, etc). Because APIs normally return JSON (and assuming you haven't mucked with formatters at all) then the runtime will convert your return type to the appropriate format.

    For MVC you should be returning ActionResult. MVC normally assumes an HTML return value. For an API-like controller action in MVC you should wrap the return value in a call to JsonResult to tell the runtime to return JSON. In that case the return type needs to be ActionResult because that is what JsonResult is derived from. Technically you could use JsonResult directly but ActionResult is generally the better route.

    0 comments No comments

  2. Yijing Sun-MSFT 7,061 Reputation points
    2022-01-27T03:12:01.767+00:00

    Hi @Santosh Umarani ,
    For MVC, you could use ActionResult and GetVersionNumber method together. The ActionResult method return view and the GetVersionNumber method return json data. By the way,you need return json data.
    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    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.

    0 comments No comments