Programing

배열을 ASP.NET MVC 컨트롤러 작업 매개 변수로 받아들이는 방법은 무엇입니까?

lottogame 2020. 10. 12. 07:02
반응형

배열을 ASP.NET MVC 컨트롤러 작업 매개 변수로 받아들이는 방법은 무엇입니까?


Designs다음 서명이있는 작업 이있는 ASP.net MVC 컨트롤러 가 있습니다.

public ActionResult Multiple(int[] ids)

그러나 URL을 사용하여이 작업으로 이동하려고 할 때 :

http://localhost:54119/Designs/Multiple?ids=24041,24117

ids매개 변수는 항상 null입니다. MVC에서 ?ids=URL 쿼리 매개 변수를 작업에 대한 배열로 변환하는 방법이 있습니까? 나는 액션 필터를 사용하는 것에 대해 이야기를 보았지만 그것이 URL 자체가 아닌 요청 데이터에서 배열이 전달되는 POST에서만 작동한다고 말할 수 있습니다.


기본 모델 바인더는 다음 URL을 예상합니다.

http://localhost:54119/Designs/Multiple?ids=24041&ids=24117

성공적으로 바인딩하려면 :

public ActionResult Multiple(int[] ids)
{
    ...
}

쉼표로 구분 된 값과 함께 작동하도록하려면 사용자 정의 모델 바인더를 작성할 수 있습니다.

public class IntArrayModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value == null || string.IsNullOrEmpty(value.AttemptedValue))
        {
            return null;
        }

        return value
            .AttemptedValue
            .Split(',')
            .Select(int.Parse)
            .ToArray();
    }
}

그런 다음이 모델 바인더를 특정 작업 인수에 적용 할 수 있습니다.

public ActionResult Multiple([ModelBinder(typeof(IntArrayModelBinder))] int[] ids)
{
    ...
}

또는 모든 정수 배열 매개 변수에 전 세계적으로 적용 Application_StartGlobal.asax:

ModelBinders.Binders.Add(typeof(int[]), new IntArrayModelBinder());

이제 컨트롤러 작업은 다음과 같습니다.

public ActionResult Multiple(int[] ids)
{
    ...
}

Darin Dimitrov의 답변 을 확장하려면 stringURL 매개 변수에서 간단한 것을 받아들이고 직접 배열로 변환하는 것이 좋습니다 .

public ActionResult Multiple(string ids){
  int[] idsArray = ids.Split(',').Select(int.Parse).ToArray();
  /* ...process results... */
}

이 작업을 수행하는 동안 구문 분석 오류가 발생하면 (누군가가 잘못된 배열을 전달했기 때문에), 예외 처리기가 엔드 포인트를 찾을 수 없을 때 MVC가 반환하는 400 Bad Request더 비 친화적 인 기본 오류 대신 오류 를 반환하도록 할 수 있습니다 404 Not Found.


이 URL 형식을 사용할 수도 있으며 ASP.NET MVC가 모든 작업을 수행합니다. 그러나 URL 인코딩을 적용하는 것을 잊지 마십시오.

?param1[0]=3344&param1[1]=2222

I don't know where Groky's URL string was coming from, but I had the same problem with some javascript calling my controller/action. It would build up a URL of null, 1, or many "IDs" from a multiple-select list (which is unique to the solution I'm going to share).

I copy/pasted Darin's custom model binder and decorated my action/parameter, but it didn't work. I still got null valued int[] ids. Even in the "safe" case where I actually did have many IDs.

I ended up changing the javascript to produce an ASP.NET MVC friendly parameter array like

?ids=1&ids=2

I had to do some silly stuff, though

ids || []                 #=> if null, get an empty array
[ids || []]               #=> if a single item, wrap it in an array
[].concat.apply([], ...)  #=> in case I wrapped an array, flatten it

So, the full block was

ids = [].concat.apply([], [ids || []])
id_parameter = 'ids=' + ids.join('&ids=')

It's messy, but it's the first time I had to hack like this in javascript.

참고URL : https://stackoverflow.com/questions/9508265/how-do-i-accept-an-array-as-an-asp-net-mvc-controller-action-parameter

반응형