DropDownList中的Ajax.ActionLink参数

时间:2013-01-25 12:07:27

标签: asp.net-mvc-4 actionlink

我有以下观点部分:

<div class="editor-label">
    @Html.LabelFor(model => model.Type)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Type, ElangWeb.Helpers.ModelHelpers.GetExerciseTypes())
</div>

我希望有一个链接,根据我的模型的Type属性生成一些partialview,它是一个Enum(我根据类型返回不同的局部视图), 我添加了以下链接:

@Ajax.ActionLink("AddExerciseItem", 
                        "AddExerciseItem",
                        "Exercise",
                        new { type=@Model.Type},
                        new AjaxOptions() { HttpMethod="GET", InsertionMode = InsertionMode.InsertBefore, UpdateTargetId="ExerciseItems"})

我的控制器操作定义如下:

public ActionResult AddExerciseItem(ExerciseType type)
{

  return PartialView("ExerciseItemOption", new ExerciseItemOption());
}

但是我没有工作,因为我的模型中有“对象引用没有设置为对象的实例”的例外。如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

您可以使用普通链接:

@Html.ActionLink(
    "AddExerciseItem", 
    "AddExerciseItem", 
    "Exercise", 
    null, 
    new { id = "add" }
)

你可以不引人注意地使用AJAXify:

// When the DOM is ready
$(function() {
    // Subscribe to the click event of the anchor
    $('#add').click(function() {
        // When the anchor is clicked get the currently
        // selected type from the dropdown list.
        var type = $('#Type').val();

        // and send an AJAX request to the controller action that 
        // this link is pointing to:
        $.ajax({
            url: this.href,
            type: 'GET',
            // and include the type as query string parameter
            data: { type: type },
            // and make sure that you disable the cache because some
            // browsers might cache GET requests
            cache: false,
            success: function(result) {
                // When the AJAX request succeeds prepend the resulting
                // markup to the DOM the same way you were doing in your
                // AJAX.ActionLink
                $('#ExerciseItems').prepend(result);
            }
        });
        return false;
    });
});

现在,您的AddExerciseItem控制器操作可以采用type参数:

public ActionResult AddExerciseItem(string type)
{
    ...
}