2012-11-05 32 views
5

Tôi muốn quay trở lại mức kỷ lục theo yêu cầu ajaxyêu cầu Ajax MVC 4.0 sử dụng C#

C# mã như:

[HttpPost] 
    public WorkoutsViewModel GetSavedWorkoutTemplate(int WorkoutId) 
    { 
     return _db.Workouts.Where(w => w.Id == WorkoutId).Select(w => new WorkoutsViewModel 
     { 
      Tag = w.Tags.FirstOrDefault(), 
      Name = w.Name, 
      MaxEffort = w.MaxEffort, 
      Id = w.Id, 
      Description = w.Description, 
      Compare = w.Compare, 
      Category = w.Category 
     }).FirstOrDefault(); 
    } 

jQuery code is:

function GetSavedWorkoutTemplate(obj) {  
    $("#Workout").hide(); 
    var WorkoutId = $(obj).val(); 
    if (WorkoutId == "") { 
     return; 
    } 
    var dto = { "WorkoutId": WorkoutId }; 

    $.ajax({ 
     type: "post", 
     url: "/MemberWorkout/GetSavedWorkoutTemplate", 
     contenttype: "application/json; charset=utf-8", 
     data: dto,  
     success: function (result) { 
      debugger; 
      $("#Workout").show(); 
     }, 
     error: function (result) { 
      alert("Unable to update status."); 
     } 
    }); 
} 

Html:

@Html.DropDownList("ddlWorkout", new SelectList(ViewBag.ddlWorkout, "Id", "Name"), "--Select Workout--", new { required = true, onchange = "GetSavedWorkoutTemplate(this);", style = "width:310px" }) 

Trong chức năng thành công, tôi nhận được kết quả là "TheGYM.We b.Models.WorkoutsViewModel "như một chuỗi không phải là một mô hình, xin vui lòng sửa tôi những gì tôi đang làm sai, tôi muốn trả lại một mô hình.

Trả lời

3

Trong C# bạn cần sử dụng Json() để sắp xếp chính xác đối tượng. Hãy thử điều này:

public ActionResult GetSavedWorkoutTemplate(int WorkoutId) 
{ 
    var workout = _db.Workouts.Where(w => w.Id == WorkoutId).Select(w => new WorkoutsViewModel 
    { 
     Tag = w.Tags.FirstOrDefault(), 
     Name = w.Name, 
     MaxEffort = w.MaxEffort, 
     Id = w.Id, 
     Description = w.Description, 
     Compare = w.Compare, 
     Category = w.Category 
    }).FirstOrDefault()); 
    return Json(workout); 
} 
+0

Lưu ý: Đừng quên thay đổi kiểu trả về của hành động cho 'ActionResult' hoặc' JsonResult'. – rcdmk

+0

@rcdmk Ah, bỏ lỡ điều đó - cảm ơn rất nhiều –

+1

Cảm ơn bạn đã làm việc ngay bây giờ –

7

Bạn phải trả lại JsonResult, không phải là đối tượng mô hình.

Thay đổi hành động của bạn như thế này:

[HttpPost] 
public ActionResult GetSavedWorkoutTemplate(int WorkoutId) 
{ 
    return Json(_db.Workouts.Where(w => w.Id == WorkoutId).Select(w => new WorkoutsViewModel 
    { 
     Tag = w.Tags.FirstOrDefault(), 
     Name = w.Name, 
     MaxEffort = w.MaxEffort, 
     Id = w.Id, 
     Description = w.Description, 
     Compare = w.Compare, 
     Category = w.Category 
    }).FirstOrDefault()); 
} 
Các vấn đề liên quan