Question

I have the following view part:

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

I want to have a link which will generate some partialview based on my model's Type property which is an Enum (I return different partial views based on the type), I've added the following link:

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

My controller action is defined as follows:

public ActionResult AddExerciseItem(ExerciseType type)
{

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

I however does not work because I have the exeption "Object reference not set to an instance of an object" for my Model. How to resolve this issue?

Was it helpful?

Solution

You could use a normal link:

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

that you could unobtrusively 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;
    });
});

Now your AddExerciseItem controller action could take the type parameter:

public ActionResult AddExerciseItem(string type)
{
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top