2017-01-03 6 views
0

좋아, 이건 내가 좋아하는 토론이다.ASP.NET MVC 단일보기로 다른 작업 논리를 처리하는 방법은 무엇입니까?

.../browse 
.../brand/audi/a4 
.../category/tail-lights-17 
.../search?t=fog+lamp 

나의 현재 솔루션은이 노선에 대해 서로 다른 행동과 뷰를 작성하는 것입니다 : 우리는 같은 경로를 가지고있다.

@if(Model.ShowCarSelection) 
{ 
    @Html.Partial("_CarSelection") 
} 

나는이 같은 시나리오를 처리 할 방법을 궁금해 모든 뷰는 부분보기로 제품을 나열하고 있지만 (내가 다른 부분도 다시이 문제를 처리 할 수있는 가정) 필터링이나 자동차 선택과 같은 몇 가지 차이점이 있습니다. 예를 들어, 다음과 같은 내용은 무엇입니까?

[HttpGet, Route("browse"), Route("/{make}/{model}"), Route("categorySlug")] 
public ActionResult List(string make, string model, string categorySlug, int page = 1, string sort, string filter) 
{ 
    var listVM = new ListVM(); 
    if(!string.IsNullOrEmpty(categorySlug)) 
    listVM.Products = productService.GetByCategorySlug(categorySlug); 
    else if (!string.IsNullOrEmpty(make)) 
    listVM.Products = productService.GetByMakeAndModel(make, model); 
    // other things like filtering, sorting, preparing car selection partial view model etc. 
    return View(); 
} 

그러나 이것은 내가 슬프고 (나쁨) 느끼게 만들 것입니다.

누구나 이와 비슷한 방법으로 나에게 지침을 줄 수 있습니까?

답변

1

모델을 만들고이를보기로 전달하면보기가 컨트롤러에 다시 게시됩니다.

public class SearchCriteria 
{ 
    public string Name { get; set; } 
    public string Model { get; set; } 
    public string CategorySlug { get; set; } 
    public int Page { get; set; } 
    public string Sort { get; set; } 
    public string Filter { get; set; } 
} 

그리고 컨트롤러 :

public ActionResult List(SearchCriteria searchCriteria) 
{ 
    // Let your service make the decision based on searchCriteria 
    productService.Get(searchCriteria); 

    // rest of your code 
} 

더 나은 아직 그래서 당신은뿐만 아니라 다른 검색을위한 모델 사용할 수있는이 작업을 수행 :

public abstract class SearchCriteria 
{ 
    public int Page { get; set; } 
    public string Sort { get; set; } 
    public string Filter { get; set; } 
} 

public class CarSearchCriteria : SearchCriteria 
{ 
    public string Name { get; set; } 
    public string Model { get; set; } 
    public string CategorySlug { get; set; } 
} 

편집

에서을 OP가 다음과 같이 묻는 코멘트 :

뷰 모델에 URL 세그먼트를 바인딩 할 수 있습니까?

질문을 명확히하기 :이 쿼리 문자열 항목이와 액션 메소드 복잡한 유형을 기대하는 경우, 그것은 쿼리 문자열에서 항목을 선택하고 어떻게 든 액션이 기대되는 모델을 만들 것인가?

예. DefaultModelBinder 클래스가 매개 변수로 복합 유형을 가진 작업 메소드를 발견하면 리플렉션을 사용하여 복합 유형의 공용 속성을 가져옵니다. 그런 다음 각 속성의 이름을 사용하고 아래 순서에 따라 다음 장소에서 일치하는 항목을 찾습니다. 이 속성 이름을 찾고 있었다 Imagin "ID"즉 예 예 예

  1. Request.Form[] 배열, Request.Form["id"]
  2. RouteData.Values[] 배열, RouteData.Values["id"]
  3. Request.QueryString[] 배열, Request.QueryString["id"]
  4. Request.Files[] 배열, Request.Files["id"]

일치 항목을 찾으면 해당 값을 사용하고 더 이상 검색하지 않습니다. . 따라서 폼에 "id"가 있고 쿼리 문자열에 "id"가 있으면 폼의 값을 사용하게됩니다. 해당 위치의 모든 부동산을 검색합니다. 모델에 복잡한 속성이있는 경우 모델에 대해 동일한 작업을 수행합니다.

+0

필터링 또는 검색 양식에 적합합니다. 'SearchCriteria' 모델로 POST 요청을 할 수는 있지만 카테고리 메뉴 링크 또는 특정 모델/모델 링크를 어떻게 생성하고 처리합니까? 모델을보기 위해 URL 세그먼트를 바인딩 할 수 있습니까? –