выпадающее значение null при использовании, viewmodel & modelbinder в asp.net mvc - PullRequest
1 голос
/ 20 июля 2009

Я использую функцию привязки модели asp.net для привязки значений формы к моей сущности при публикации из представления.

HTML отображается правильно в начальном представлении с правильными параметрами и значениями элементов.

При заполнении формы и публикации все значения правильно вводятся в сущность, кроме значения из раскрывающегося списка. не уверен, что я делаю не так.

код прилагается ниже:

Клиент:

 public class Customer : EntityBase
    {
        public virtual string Name { get; set; }
        public virtual string Email { get; set; }
        public virtual string Mobile { get; set; }
        public virtual Store LocalStore { get; set; }
        public virtual DateTime? DateOfBirth { get; set; }

        public Customer(){}

        public Customer(string name, string email, string mobile, Store localStore):this(name, email, mobile, localStore, null)
        {
        }

        public Customer(string name, string email, string mobile, Store localStore, DateTime? dateOfBirth)
        {
            Name = name;
            Email = email;
            Mobile = mobile;
            LocalStore = localStore;
            DateOfBirth = dateOfBirth;
        }
    }

ViewModel:

 public class CustomerViewModel {

        // Properties
       private IStoreRepository _StoreRepository;
       public Customer Customer { get; private set; }
       public SelectList Stores { get; private set; }

        // Constructor
        public CustomerViewModel(IStoreRepository storeRepository, Customer customer)
        {
            _StoreRepository = storeRepository;
            Customer = customer;
                Stores = new SelectList(_StoreRepository.GetAllStores(), "Id", "Name", Customer.LocalStore.Id);

        }
    }

Контроллер:

 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind(Prefix="")]Customer customer)
        {
            return View(new CustomerViewModel(_StoreRepository, customer));
        }

Вид:

<%@ Import Namespace="BlackDiamond.Buzz.MVCWeb.Controllers"%>
<%@ Import Namespace="BlackDiamond.Buzz.Core"%>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CustomerViewModel>" %>
<%
    Customer customer = ViewData.Model.Customer;
    using (Html.BeginForm())
    {
    %>    
    <table>
        <tr>
            <td>Local Store:</td>
            <td><%= Html.DropDownList("LocalStore", ViewData.Model.Stores)%></td>
         </tr>
         <tr>
            <td>Name:</td><td><%= Html.TextBox("Name", customer.Name)%></td>
         </tr>
         <tr>
            <td>Email:</td><td><%= Html.TextBox("Email", customer.Email)%></td>
        </tr>
        <tr>
            <td>Mobile:</td><td><%= Html.TextBox("Mobile", customer.Mobile)%></td>
        </tr>
    </table>
    <input type="submit" value="Create" />
<%}%>

Ответы [ 2 ]

1 голос
/ 21 июля 2009

Пришлось создать настраиваемое связыватель моделей для извлечения сущности Store на основе guid из выпадающего списка:

    public class CustomerModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(Customer))
        {
            // get values
            string name = bindingContext.ValueProvider["Name"].AttemptedValue;
            string email = bindingContext.ValueProvider["Email"].AttemptedValue;
            string mobile = bindingContext.ValueProvider["Mobile"].AttemptedValue;
            Guid storeId = new Guid(bindingContext.ValueProvider["LocalStore"].AttemptedValue);
            Store localStore = IoC.Container.Resolve<IStoreRepository>().GetStore(storeId);

            // hydrate
            return new Customer(name, email, mobile, localStore);
        }
        else
        {
            return null;
        }
    }
}
1 голос
/ 21 июля 2009

Может быть, потому что вы объявляете LocalStore типом хранилища?

public virtual Store LocalStore { get; set; }

Я думаю, что это должно быть int (если свойство "id" равно int) или строка. Хотя не уверен.

public virtual int LocalStore { get; set; }
...