0

我有以下视图部分:

<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 属性生成一些部分视图,该属性是一个枚举(我根据类型返回不同的部分视图),我添加了以下链接:

@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());
}

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

4

1 回答 1

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控制器操作可以采用类型参数:

public ActionResult AddExerciseItem(string type)
{
    ...
}
于 2013-01-25T12:12:48.920 回答