2017-04-15 182 views
0

我在ASP.net MVC應用程序工作時到達不綁定,我有一個產品表作爲截圖所示:視圖模型屬性在控制器

table of products

我希望能夠過濾該產品表,並且我希望通過查詢字符串參數(作爲GET)進行過濾,以便可以共享該URL。

視圖模型的頁面是這樣的:

public class InventoryReportViewModel 
{ 
    public SearchViewModel Search { get; set; } // 2 string props [Type and Term] 
    public IEnumerable<ProductViewModel> Products { get; set; } 
    public PaginationViewModel Pagination { get; set; } // 3 int props [currentPage, recordsPerPage, totalRecords] 
} 

我用剃刀助手繪製濾波器的輸入,如:

@Html.EditorFor(m => m.Search.Term, new { htmlAttributes = new { @class = "form-control" } }) 

同時,我已經建立了我形成使用GET像這樣:

@using (Html.BeginForm("Inventory", "Report", FormMethod.Get)) 
{ 
    // form elements 
} 

ReportController.cs具有以下甲基OD,是有關在這裏我的問題:

public ActionResult Inventory(string SearchTerm, string SearchType, int page = 1) 
{ 
    var viewModel = _reportService.GetProducts(page, SearchTerm, SearchType); 
    return View(viewModel); 
} 

當我通過一個搜索詞,然後單擊篩選結果按鈕,我到達我上面的控制器的方法,但SearchTermSearchTypenull

我知道如何「破解」這個工作,例如,如果我這樣做:

<input type="text" name="SearchTerm" class="form-control"/> 

然後搜索詞我輸入將由控制器回升,但有沒有其他辦法?

回答

1

既然你已經做了viewmodelSearch

public SearchViewModel Search { get; set; } 

你只需要把它傳遞給控制器​​這樣

public ActionResult Inventory(SearchViewModel Search, int page = 1 
{ 
    var viewModel = _reportService.GetProducts(page, Search.Term, Search.Type); 
    return View(viewModel); 
} 

你越來越null因爲textboxes被命名爲Search.Term是爲什麼它不符合參數。

+0

感謝@Usman,工作。 – Ciwan

0

的形式應該是後

@using (Html.BeginForm("Inventory", "Report", FormMethod.Post)) 
{ 
    // form elements 
} 

這也可以是清潔:

@Html.EditorFor(m => m.Search.Term, new { htmlAttributes = new { @class = "form-control" } }) 

@Html.EditorFor(m => m.Search.Term, new { @class = "form-control" }) 

另一個問題, 在Razor視圖,你有第一行指定模型?