/ / DropDownListPara que a seleção não seja salva - asp.net-mvc

DropDownListPara que a seleção não seja salva - asp.net-mvc

Eu sou novo no MVC. Eu estou usando um DropDownListFor para exibir uma lista de nomes de empresas e, com base na seleção feita, preenchendo outros campos do cliente. Os campos do cliente estão sendo preenchidos corretamente, mas quando tento POSTAR o registro, recebo um erro de validação "O nome da empresa é obrigatório", mesmo que o nome da empresa tenha sido selecionado no DropDownListFor. Aqui está o ViewModel:

     namespace CMSUsersAndRoles.Models
{
public class QuoteViewModel
{   [Key]
[Display(Name = "Quote Id")]
public int QuoteId { get; set; }
// Columns from Customer table
[Required(ErrorMessage = "Please select a company")]
[Display(Name = "Customer Id")]
public int? CustomerId { get; set; }
[Display(Name = "Sales Rep")]
public string SalesRep { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public string Company { get; set; }
[Display(Name = "Address 1")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[StringLength(10)]
[Display(Name = "Zip Code")]
[RegularExpression(@"^d{5}(-d{4})?$", ErrorMessage = "Invalid Zip Code")]
public string PostalCode { get; set; }
[Phone]
[Display(Name = "Work Phone")]
public string WorkPhone { get; set; }
[Phone]
[Display(Name = "Cell Phone")]
public string CellPhone { get; set; }
[EmailAddress]
public string Email { get; set; }
[Range(0, 100)]
public decimal? Discount { get; set; }
[Display(Name = "Payment Terms")]
public int? PaymentTerms { get; set; }
// Columns from QuoteDetail table
[Display(Name = "Quote Detail")]
public List<QuoteDetail> QuoteDetail { get; set; }
// Columns from Quote table


public decimal Subtotal { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Quote Date")]
public DateTime? QuoteDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Good Until")]
public DateTime? GoodUntil { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Quote Sent")]
public DateTime? QuoteSent { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date Approved")]
public DateTime? DateApproved { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date Ordered")]
public DateTime? DateOrdered { get; set; }

}
}

Aqui está o código da Vista:

    @Html.DropDownListFor(model => model.CustomerId, new SelectList(ViewBag.Customers, "CustomerId", "Company"), "---Select one---", new { htmlAttributes = new { @class = "company" } });
@Html.HiddenFor(model => model.Company)
@Html.ValidationMessageFor(model => model.Company, "", new { @class = "text-danger" })

Aqui está o Get:

public ActionResult Create()
{
QuoteViewModel qvm = new QuoteViewModel();

var customers = db.Customers.ToList();
ViewBag.Customers = customers;

return View(qvm);
}

E aqui está o código para o POST:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QuoteViewModel qvm)
{

if (ModelState.IsValid)
{
Quote quote1 = new Quote();

quote1.CustomerId = qvm.CustomerId;
...
customer.CustomerId = (int)qvm.CustomerId;
...
customer.Company = qvm.Company;

db.Entry(customer).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{

var objContext = ((IObjectContextAdapter)db).ObjectContext;
// Get failed entry
var entry = ex.Entries.Single();
// Now call refresh on ObjectContext
objContext.Refresh(RefreshMode.ClientWins, entry.Entity);


}


return RedirectToAction("Index");
}

var customers = db.Customers.ToList();
ViewBag.Customers = customers;

return View(qvm);
}

o que estou perdendo? Qualquer ajuda será muito apreciada.

Respostas:

0 para resposta № 1

Eu não estava definindo o valor do HiddenFor abaixo. Obrigado, @StephenMuecke.

@Html.HiddenFor(model => model.Company)