MVC.Net binding complex models?

ε祈祈猫儿з 提交于 2019-12-04 18:18:44

I suppose you're looking for what this blog article describes: ASP.NET MVC Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries

Quote from the blog:

If the signature looks like this:

public ActionResult Blah(IDictionary<string, Company> stocks) {
  // ...
}

And we are given this in HTML:

<input type="text" name="stocks[0].Key" value="MSFT" />
<input type="text" name="stocks[0].Value.CompanyName" value="Microsoft Corporation" />
<input type="text" name="stocks[0].Value.Industry" value="Computer Software" />
<input type="text" name="stocks[1].Key" value="AAPL" />
<input type="text" name="stocks[1].Value.CompanyName" value="Apple, Inc." />
<input type="text" name="stocks[1].Value.Industry" value="Consumer Devices" />

Which like this:

stocks[0].Key = "MSFT"
stocks[0].Value.CompanyName = "Microsoft Corporation"
stocks[0].Value.Industry = "Computer Software"
stocks[1].Key = "AAPL"
stocks[1].Value.CompanyName = "Apple, Inc."
stocks[1].Value.Industry = "Consumer Devices"

Then it will be just as if we had written:

stocks = new Dictionary<string, Company>() {
  { "MSFT", new Company() { CompanyName = "Microsoft Corporation", Industry = "Computer Software" } },
  { "AAPL", new Company() { CompanyName = "Apple, Inc.", Industry = "Consumer Devices" } }
};

This IMO is how you should be handling this:

Pass customerID in your viewbag if you're really not wanting to make a viewmodel (p.s. It is ok to make a viewmodel!)

public class OrderController : Controller
{
   public ActionResult Create(int customerID)
   {
      ViewBag.CustomerID = customerID
      Order ord = new Order(o);
      return View(ord);
   }
}

your post method:

[HttpPost]
public ActionResult Create(int CustomerID, Order order)
{
  //create your order
}

your cshtml

@model Company.Application.Model.Order;

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
    @Html.TextBoxFor(o => o.ItemName)
    @Html.TextBoxFor(o => o.SomeDate)
    @Html.Hidden("CustomerID",ViewBag.CustomerID)
    <input type="submit" value="Add" />
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!