Darf Zon
Darf Zon

Reputation: 6378

How update this div using Ajax?

This is my razor view. The main point is when I the dropdown value change, update the question-editor div. As you can see, I'm invoking an EditorFor.

@model Contoso.MvcApplication.Models.Question.CreateQuestionViewModel

@{
    ViewBag.Title = "Create Open Question";
}

<h3>Create Question</h3>

<select id="question-type-dropdown" style="margin-bottom: 20px;">
    <option value="MC">Multiple Choice</option>
    <option value="O">Open Question</option>
</select>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        @Html.HiddenFor(model => model.QuestionSetId)
        <legend>Question Template</legend>

        <div id="question-editor">
            @Html.EditorFor(model => model.Template, "_QuestionEditorBoxPartial")
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

Here is the partial view, just contain an EditorModelFor to choose which viewtemplate should it use.

_QuestionEditorBox (PartialView)

@model Contoso.Core.Base.QuestionTemplate
@Html.EditorForModel(Contoso.Core.QuestionRepositoryManager.GetQuestionTemplateView(Model))
public abstract class Question
{
   public int Id {get;set;}
   public string QuestionText { get; set; }
}

public OpenQuestion : Question { ... }
public MultipleChoiceQuestion : Question { ... }

public class CreateQuestionViewModel
{
    public int QuestionSetId { get; set; }
    public QuestionTemplate Template { get; set; }
}

But when I did this, it does not display anything because I'm doing EditorFor two times with the same model. I tried to change the first EditorFor with a PartialView, but this is not gonna work because I need that the model binder catches my model.

EDIT (AJAX METHOD):

$("#question-type-dropdown").change(function () {
    $.get("/Question/UpdateQuestionEditorBox", { questionType: $(this).val() },
        function (data) {
            $("#question-editor").html(data);
        });
});

Upvotes: 0

Views: 457

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

One possibility is to use a partial (not an editor template):

<div id="question-editor">
    @Html.Partial("_QuestionEditorBox.cshtml", Model.Template)
</div>

And then inside your partial:

@model Contoso.Core.Base.QuestionTemplate
@{
    ViewData.TemplateInfo.HtmlFieldPrefix = "Template";
}
@Html.EditorForModel(Contoso.Core.QuestionRepositoryManager.GetQuestionTemplateView(Model))

Notice how I did set the HtmlFieldPrefix in order to preserve the navigational context into the partial and so generate proper names for the input fields in the corresponding editor template.

Also you mentioned updating the question-editor div with an AJAX call when the dropdown selection changes but you haven't shown any AJAX code to do that. I guess you have subscribed to the .change event of the dropdown somewhere and triggered an AJAX call.

Upvotes: 2

Related Questions