Using an interface as the model type of a partial view + data annotations

后端 未结 3 1224
北海茫月
北海茫月 2021-01-05 03:44

I have a case where a complex partial view needs different validation of fields depending on where the partial view is used.

I thought I could get around this by mak

3条回答
  •  死守一世寂寞
    2021-01-05 03:57

    Ann, you're right. I've deleted my comment. You can't post an interface back through your view. However, I don't know what exactly your trying to do since I can't see your code. Maybe something like this? I'm passing an interface to the view, but passing it back as the class I'm expecting. Again, I'm not sure the application is here.

    Let's say you have classes like this:

    [MetadataType(typeof(PersonMetaData))]
    public class Customer : IPerson {
        public int ID { get; set; }
        public string Name { get; set; }
         [Display(Name = "Customer Name")]
        public string CustomerName { get; set; }
    }
    
    public class Agent : IPerson {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    
    public partial class PersonMetaData : IPerson {
        [Required]
        public int ID { get; set; }
    
        [Required]
        [Display(Name="Full Name")]
        public string Name { get; set; }
    }
    
    public interface IPerson {
        int ID { get; set; }
        string Name { get; set; }
    }
    
    public interface IAgent {
        int AgentType { get; set; }
    }
    
    public interface ICustomer {
        int CustomerType { get; set; }
    }
    

    Your Controller looks like:

        public ActionResult InterfaceView() {
            IPerson person = new Customer {
                ID = 1
            };
            return View(person);
        }
    
        [HttpPost]
        public ActionResult InterfaceView(Customer person) {
            if (ModelState.IsValid) {
                TempData["message"] = string.Format("You posted back Customer Name {0} with an ID of {1} for the name: {2}", person.CustomerName, person.ID, person.Name);
            }
            return View();
        }
    

    And your View Looks like this:

    @model DataTablesExample.Controllers.Customer
    
    
    
    
    @if (@TempData["message"] != null) {
        

    @TempData["message"]

    } @using (Html.BeginForm()) { @Html.ValidationSummary(true)
    IPerson @Html.HiddenFor(model => model.ID)
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
    @Html.LabelFor(model => model.CustomerName)
    @Html.EditorFor(model => model.CustomerName) @Html.ValidationMessageFor(model => model.CustomerName)

    }

提交回复
热议问题