나는 Ajax 바인딩 된 Razor가있는 MVC 3 애플리케이션에서 Telerik MVC 그리드를 사용하고 있습니다. 이제는 사용자가 편집 모드에서 사용할 수 있도록 드롭 목록 열을 추가하려고 시도하지만이를 파악할 수는 없습니다. 그리드에는 제품 목록이 표시되며 드롭 목록에 Product를 연결할 수있는 ProductCategories 컬렉션이 포함되도록하고 싶습니다. 나는 지금 몇 시간 동안이 일을 해왔고 아이디어가 없습니다. 나는 여기 누군가가 도울 수 있기를 정말로 바란다 :Telerik MVC Grid : 열에 DropDownList를 사용하는 방법?
나는 telerik 데모를 참조하고 있는데, 이것은 here이다.
나를 매달고있는 부분은 데모가 사용하는 도움말보기에 있다고 생각합니다. 이 데모에서는 "ClientEmployee (Editor)"라고합니다. 제 경우에는 "ProductCategoryDropList.cshtml"이라는 파일에 도우미를 배치했습니다. 이 도우미에서 DropDownList를 올바르게 바인딩하는 데 어려움을 겪고 있습니다. 어떻게 든 올바른 데이터로 BindTo() 메서드를 설정하지 않기 때문에이 문제가 발생할 수 있다고 생각합니다. "new SelectList()"생성자 호출의 첫 번째 매개 변수로 "SomeCollectionReference"와 함께 아래의 예제 DropDownList Helper 코드에서이 혼란을 지적했습니다. 그 자리에 "Model"을 넣으려고하면 NullReferecne 예외가 발생합니다. 목록이 포함 된 ViewBag 데이터에 액세스하려고하면 "SelectList에 ProductCategoryID 열이 없습니다"와 비슷한 메시지가 표시됩니다. 그래서, 나는 무엇을 시도해야할지 모르겠습니다.
내 문제에 대한 설명이 얼마나 명확한지는 잘 모르겠지만, 완성을위한 노력의 일환으로 아래에 관련 있다고 생각되는 코드를 포함 시켰습니다.
컨트롤러 :
public ActionResult Index()
{
ViewBag.ProductCategories = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductcategoryName");
var products = _productService.GetProducts().ToList();
var presentationModel = _mapper.MapAsList(products);
return View(presentationModel);
}
//
// GET: /Product/
[GridAction]
public ViewResult _Index()
{
ViewBag.ProductCategories = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductcategoryName");
return View(new GridModel<ProductPresentationModel>
{
Data = _mapper.MapAsList(_productService.GetProducts().ToList())
});
}
보기 : 나는 배치하여 그것을 단순화하기 위해 노력했습니다
이 조금 긴하지만, 다음에 "// < --- DropList 여기에" 내가 함께 일하려고하는 칼럼에.
@model IEnumerable<Models.PresentationModels.ProductPresentationModel>
@(Html.Telerik().Grid(Model).HtmlAttributes(new { style = "width: 100%;" })
// Give the Grid an HTML id attribute value
.Name("ProductGrid")
// Establish the promiry key, to be used for Insert, Update, and Delete commands
.DataKeys(dataKeys => dataKeys.Add(p => p.ProductID))
// Add an Insert command to the Grid Toolbar
.ToolBar(commands => commands.Insert().ButtonType(GridButtonType.ImageAndText))
// Using Ajax Data Binding to bind data to the grid
.DataBinding(dataBinding => dataBinding
// Ajax Binding
.Ajax()
.Select("_Index", "Product")
// Home.Insert inserts a new data record
.Insert("Create", "Product")
// Home.Update updates an existing data record
.Update("Edit", "Product")
// Home.Delete deletes an existing data record
.Delete("Delete", "Product")
)
.Columns(columns =>
{
columns.Bound(p => p.ProductName).Width(120);
columns.Bound(p => p.ProductDescription).Width(150);
columns.Bound(p => p.PricePerMonth).Width(120);
columns.Bound(p => p.ProductImagePath).Width(150)
columns.Bound(p => p.ProductActive).Width(120)
.ClientTemplate("<input type='checkbox' disabled='disabled' name='Active' <#= ProductActive ? checked='checked' : '' #> />");
columns.Bound(p => p.ProductCategoryName); // <--- DropList Here
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Image);
commands.Delete().ButtonType(GridButtonType.Image);
});
})
.Editable(editing => editing.Mode(GridEditMode.PopUp))
.ClientEvents(events => events.OnEdit("onEdit"))
.Pageable()
.Scrollable()
.Sortable()
.Filterable()
)
@section HeadContent {
<script type="text/javascript">
function onEdit(e) {
$(e.form).find('#ProductCategoryName').data('tDropDownList').select(function (dataItem) {
return dataItem.Text == e.dataItem['ProductCategoryName'];
});
}
</script>
}
모델 :
[DisplayName(@"Category Name")]
[UIHint("ProductCategoryDropList"), Required]
[StringLength(255, ErrorMessage = @"Product Category Name cannot be more than 255 characters in length")]
public string ProductCategoryName
{
get
{
string name = string.Empty;
if (_model.ProductCategory != null)
{
name = _model.ProductCategory.ProductCategoryName;
}
return name;
}
set
{
if (_model.ProductCategory != null)
{
_model.ProductCategory.ProductCategoryName = value;
}
}
}
DropList 도우미 :
@model Models.PresentationModels.ProductPresentationModel
@(Html.Telerik().DropDownList()
.Name("ProductCategoryName")
.BindTo(new SelectList(<SomeCollectionReference>, "ProductCategoryID", "ProductCategoryName"))
)
ProductMapper :
public List<ProductPresentationModel> MapAsList(List<Product> products)
{
//var categoryList = new SelectList(_productCategoryService.GetProductCategories().ToList(), "ProductCategoryID", "ProductCategoryName");
var presentationModels = products
.Select(x => new ProductPresentationModel()
{
ProductID = x.ProductID,
ProductCategoryID = ((x.ProductCategory != null) ? x.ProductCategory.ProductCategoryID : 0),
ProductCategoryName = ((x.ProductCategory != null) ? x.ProductCategory.ProductCategoryName : String.Empty),
ProductName = x.ProductName,
ProductDescription = x.ProductDescription,
PricePerMonth = x.PricePerMonth,
ProductImagePath = x.ProductImagePath,
ProductActive = x.ProductActive,
ProductCategories = new SelectList(_productCategoryService.GetProductCategories().ToList(), "ProductCategoryID", "ProductCategoryName")//categoryList
}).ToList();
return presentationModels;
}
훌륭한 정보, Ondrej. 이 게시물을 예제 또는 두 가지로 업데이트하여 설명 한 내용을 설명 할 수 있습니까? – campbelt