我有以下实体:

public class Category
{
    public virtual int CategoryID { get; set; }

    [Required(ErrorMessage = "Section is required")]
    public virtual Section Section { get; set; }

    [Required(ErrorMessage = "Category Name is required")]
    public virtual string CategoryName { get; set; }
}

public class Section
{
    public virtual int SectionID { get; set; }
    public virtual string SectionName { get; set; }
}

现在,在我的添加类别视图中,我有一个文本框来输入extionID EG:

<%= Html.TextBoxFor(m => m.Section.SectionID) %>

我想创建一个自定义模型活页夹以具有以下逻辑:

如果模型密钥以ID结束并具有一个值(将值插入文本框中),则将父对象(示例中的段)设置为extifs.getById(value Emented),否则将父对象设置为null。

我真的很感谢这里的帮助,因为这让我感到困惑了一段时间。谢谢

有帮助吗?

解决方案 2

使用Dave Thieben发布的解决方案,我提出了以下内容:

public class CustomModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (bindingContext.ModelType.Namespace.EndsWith("Models.Entities") && value != null && (Utilities.IsInteger(value.AttemptedValue) || value.AttemptedValue == ""))
        {
            if (value.AttemptedValue != "")
                return Section.GetById(Convert.ToInt32(value.AttemptedValue));
            else
                return null;
        }
        else
            return base.BindModel(controllerContext, bindingContext);
    }
}

这很好地工作,但是当将表格发布回来并使用下拉列表时,它不会选择正确的值。我明白了为什么,但是到目前为止,我的修复尝试已经徒劳无功。如果您能提供帮助,我将再次感谢它。

其他提示

我在 这个问题 如果存在的话,那就使用iRepository填充外国钥匙。您可以修改它以更好地适合自己的目标。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top