MVC Привязка коллекции подтипов к модели поста

Моя проблема: чтобы получить текущий подтип Вопроса, я не могу просто вызвать GetValue("ModelType"), так как Вопросы - это коллекция. Итак, как мне получить подтип для текущего Вопроса в коллекции в пользовательском Связывателе моделей? Так что это не сработает:

var typeValue = bindingContext.ValueProvider.GetValue("ModelType");

Вот несколько упрощенная версия моего кода.. У меня есть следующая модель:

public class PostViewModel
{
    public string Title { get; set; }
    public List<Question> Questions { get; set; }
}

public class Question
{
    public int Id { get; set; }
}

public class SingleChoice : Question
{
    public List<Answers> AnswerOptions { get; set; }
}
public class TextQuestion : Question
{
    public string Value { get; set; }
}

Затем я создал следующую модель связующего:

public class QuestionModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        if (modelType.Equals(typeof(Question)))
        {

            var typeValue = bindingContext.ValueProvider.GetValue("ModelType");
            var type = Type.GetType(
                (string)typeValue.ConvertTo(typeof(string)),
                true
            );
            if (!typeof(Question).IsAssignableFrom(type))
            {
                throw new InvalidOperationException("Bad Type");
            }


            var obj = Activator.CreateInstance(type);                
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => obj, type);
            bindingContext.ModelMetadata.Model = obj;
            return obj;
        }

        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

И мой взгляд выглядит так:

// Просмотр A

@model PostModel

@Html.EditorFor(m => m.Questions)

// Вид B

@model QuestionViewModel
<div>
@Html.HiddenFor(m => m.Id)
@Html.Hidden("ModelType", Model.GetType())
@switch (Model.QuestionType)
{
    case QuestionType.OpenText:
        @Html.Partial("EditorTemplates/Types/TextViewModel", Model)
        break;
    case QuestionType.SingleChoice:
    @Html.Partial("EditorTemplates/Types/SingleChoiceViewModel", Model)
        break;

}
</div>

0 ответов

Другие вопросы по тегам