0

This is my ViewModel

public class SaleOrderViewModel
{
    public SO SaleOrder { get; set; }
    public List<SOD> SaleOrderDetail { get; set; }
    public IQueryable<Product> Products { get; set; }
    public Product Product { get; set; }

}

i want to post and validate only some properties of SaleOrder and SaleOrderDetail. other properties are null or not required for posting.

this is my post method

[HttpPost]
[ValidateAntiForgeryToken]    
public ActionResult Create([SaleOrderViewModel saleOrderViewModel)
    {
        if (ModelState.IsValid)
        {
           //more code
        }
    }  

but ModelState.IsValid is always false.

how i can include and bind only some properties of view model?

Waqas Javaid
  • 155
  • 1
  • 10
  • 3
    View models do not contain data models (especially when editing) - they contain only the properties of your data models that you need in the view - refer [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Aug 12 '18 at 04:20
  • To expand a bit on Stephen's comment, end of day, you'll have to _map_ your VM to your data model, so you'll have to provide some "default" value _required_ by your data model and account for that in your application. Hth. – EdSF Aug 12 '18 at 17:31
  • @stephenMuecke I read article you suggested. Basically I am building a simple sale order form. I am passing `Products` list in ViewModel which I have to show to user. User will select products from list, enter quantity, discount, amount paid etc. Other ViewModel classes are `SaleOrder` and `SaleOrderDetail`. These will be filled and post back by user. I want all models in one bundle that I am supposing to call as “ViewModel”. Isn’t it? Or some better approach you suggests. – Waqas Javaid Aug 13 '18 at 09:27
  • But you are not using a view model (despite the fact you named it 'SaleOrderViewModel'). View models (when editing) should not contain data models –  Aug 13 '18 at 09:40

1 Answers1

0

after a bit research and trying different things. i come up with a solution

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Prefix = "SaleOrder", Include = "BillAmount,Balance")] SO sO, [Bind(Prefix = "SaleOrderDetail", Include = "ProductId,Quantity")] List<SOD> sOD)
    {
        if (ModelState.IsValid)
        {
            sO.CustomerId = 10;
            sO.Date = DateTime.Now;
            sO.SaleReturn = false;
            db.SOes.Add(sO);
            db.SaveChanges();
            foreach (SOD sod in sOD)
            {
                sod.SOId = sO.Id;
            }

            db.SODs.AddRange(sOD);

            db.SaveChanges();
            return RedirectToAction("Index");
        }

i am delighted but i could not understand that how post method enable to take two arguments automatically?

in view i have bind my ViewModel like this.

@model MYBUSINESS.Models.SaleOrderViewModel
Waqas Javaid
  • 155
  • 1
  • 10