2011-01-17 6 views
1

드롭 다운 목록 클라이언트 템플릿을 사용할 때 내 컨트롤러에서 내 아약스 .Update ("_ SaveAjaxEditing", "AptProfile")에 null 값이 전달됩니다. 내 그리드에 바인딩 내 FormViewModel에서Telerik MVC Grid 템플릿 편집 DropDownList 문제

속성 :

[AcceptVerbs(HttpVerbs.Post)] 
    //[CultureAwareAction] 
    [GridAction] 
    public ActionResult _SaveAjaxEditing(int id, int? BuildingGrid) 
    { 
     ApartmentProfileRepository repo = new ApartmentProfileRepository(); 
     AptProfile profile = repo.Get(id); 

     TryUpdateModel(profile); 
     repo.Save(); 
     return View(new GridModel(GetAllProfiles())); 
    } 

답변

0

은 첫째, 당신이 필요 : 여기

<%= Html.Telerik().Grid<PayRent.Models.AptProfileFormViewModel1>() 
        .Name("Profiles") 
        .DataKeys(dataKeys => dataKeys.Add(c => c.AptProfileID)) 
            .ToolBar(commands => commands.Insert()) 
        .DataBinding(binding => 
         { 
          binding.Ajax() 
          .Select("GetProfiles", "AptProfile") 
          .Insert("_InsertAjaxEditing", "AptProfile") 
          .Update("_SaveAjaxEditing", "AptProfile") 
          .Delete("_DeleteAjaxEditing", "AptProfile"); 

         }) 

        .Columns(columns => 
        { 
         columns.Bound(o => o.AptProfileID); 
         columns.Bound(o => o.BuildingID); 
         columns.Bound(o => o.AptID); 
         columns.Bound(o => o.AptRate); 
         columns.Bound(o => o.AptSize); 
         columns.Bound(o => o.MoveInDate); 
         columns.Command(s => 
         { 
          s.Edit(); 
          s.Delete(); 


         }); 


        }) 
            .Editable(editing => editing.Mode(GridEditMode.InLine)) 
            .ClientEvents(events => events.OnEdit("onEdit")) 
        .Pageable() 
      %> 
    </p> 

<script type="text/javascript"> 

function onEdit(e) { 
//   $(e.form).find('#BuildingsGrid').data('tDropDownList').select(function (dataItem) { 
//    return dataItem.Text == e.dataItem['BuildingGrid']; 
//   }); 
     } 


    </script> 



My EditTemplate: 

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
<%= Html.Telerik().DropDownList() 
     .Name("BuildingsGrid") 
      .BindTo(new SelectList((IEnumerable)ViewData["Buildings"], "BuildingID", "Name")) 
%>) 

내 컨트롤러입니다 : 여기
[UIHint("BuildingsGrid"), Required] 
       [DisplayName("Building ID")] 
       public int BuildingID 
       { 
        get; 
        set; 
       }). 

내이다 뷰의 컬럼 이름을 편집 템플리트 및 컨트롤러 조치 매개 변수의 이름과 일치시킵니다. int 매개 변수가 컨트롤러 동작에서 nullable 일 필요가 있다고 생각하지 않습니다.

그런 다음 컨트롤러 작업에서 편집 템플릿의 ViewData [ "건물"]을 설정해야합니다. 보기를 리턴하기 전에 프로파일 오브젝트에서 현재 값을 선택하십시오.

public ActionResult _SaveAjaxEditing(int id, int BuildingsGrid) 
    { 
     ApartmentProfileRepository repo = new ApartmentProfileRepository(); 
     AptProfile profile = repo.Get(id); 

     // Save the building ID in the profile 
     profile.BuildingID = BuildingsGrid; 

     TryUpdateModel(profile); 
     repo.Save(); 

     // Load the Building objects into the ViewData 
     ViewData["Buildings"] = GetBuildings(); 

     return View(new GridModel(GetAllProfiles())); 
    } 
+0

윙거, ViewData를 사용하지 않고이를 수행 할 수있는 방법이 있습니까? 내 모델에서 SelectList 속성에 액세스하여이를 수행하는 방법을 알아 내려고했지만이를 해결하지 못했습니다. – campbelt

+1

campbelt, 도우미 개체를 사용하여 건물 개체의 목록을 반환하는 방법은 무엇입니까? 편집 템플리트에서 ViewData를 도우미 클래스 메소드로 바꿉니다. 그리드 데이터가 바인딩되기 전에 한 번만 렌더링 된 다음 각 행에 대해 동일한 목록이 사용된다는 점을 기억하십시오. – Winger

+0

고마워, 윙어. 나는 그것을 들여다 볼 것이다. 그 동안 내가 볼 수있는 이런 종류의 좋은 예를 알게됩니까? – campbelt

3

모든 것을 유지하려면, 뷰백을 사용하지 않아야합니다. 내 콤보 상자는 별도의 편집기 템플릿에 있습니다. SelectList를 JsonResult로 반환하면됩니다. 즉, 사용자가 페이지에있는 동안 해당 콤보 상자의 데이터가 변경 될 것으로 예상되는 경우 콤보가 열릴 때마다 서버 메서드를 호출하기 때문에 그렇게하는 것이 좋습니다.

아래 예에서 사용자는 카테고리를 선택하는 것과 동일한 페이지에 카테고리를 추가 할 수 있기 때문에 매번 서버를 쳐야합니다. 하지만 다른 페이지에서는 ViewBag/ViewData를 통해 서버 측 바인딩을 사용하므로 서버에 한 번만 도달합니다.

내 편집기 템플릿 : 컨트롤러에서 다음

@(Html.Telerik().ComboBox() 
.Name("YourNameGoesHere") 
.DataBinding(binding => binding.Ajax().Select("SelectCategoriesForComboBox","Shared"))) 

:

public EquipmentEntities db = new EquipmentEntities(); 
public List<SelectListItem> CategoryList 
{ 
    get 
    { 
     var m = db.Categories 
     .Select(e => new{ Id = e.Id, Name = e.Name }) 
     .OrderBy(e => e.name); 
     List<SelectListItem> sl = new SelectListItem(m.ToList(), "Id", "Name").ToList(); 

     //insert a blank item as the first entry 
     sl.Insert(0, (new SelectListItem { Text = "", Value = string.Empty })); 
     return sl; 
    } 
} 

[HttpPost] 
public ActionResult SelectCategoryForComboBox() 
{ 
    return new JsonResult { Data = CategoryList }; 
} 

은 어쩌면 내가 늦게 조금 해요,하지만 희망 누군가를하는 데 도움이됩니다.