5

我想通过ajax请求返回一条记录

C#代码如下:

    [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代码是:

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" })

在成功函数中,我得到的结果是“TheGYM.Web.Models.WorkoutsViewModel”作为字符串而不是模型,请纠正我做错了什么,我想返回一个模型。

4

2 回答 2

7

您必须返回 JsonResult,而不是模型对象。

将您的操作更改为:

[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());
} 
于 2012-11-05T14:16:51.670 回答
3

在 C# 中,您需要使用Json()正确序列化对象。尝试这个:

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);
}
于 2012-11-05T14:14:12.740 回答