jquery – 使用c#的Ajax请求MVC 4.0

前端之家收集整理的这篇文章主要介绍了jquery – 使用c#的Ajax请求MVC 4.0前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想通过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”作为字符串而不是模型,请纠正我的错误,我想要返回一个模型.

最佳答案
在C#中,您需要使用Json()来正确地序列化对象.试试这个:

public ActionResult GetSavedWorkoutTemplate(int WorkoutId)
{
    var workout = _db.Workouts.Where(w => w.Id == WorkoutId).Select(w => new Workoutsviewmodel
    {
        Tag = w.Tags.FirstOrDefault(),Category = w.Category
    }).FirstOrDefault());
    return Json(workout);
}

猜你在找的jQuery相关文章