如何在c# MVC中分配部分视图数据给模型

本文关键字:视图 数据 模型 分配部 MVC | 更新日期: 2023-09-27 18:06:52

我使用MVC c#和实体框架。

在我的局部视图中,我想改变data

这是我的控制器

public ActionResult BusinessDetails(){               
    int bsId = bskey ?? default(int);
    var BusinessQuery = GetBusinessById(bsId);    
    var PeopleQuery = BusinessQuery.t_PEOPLE
                        .Where(p => p.PP_IS_CONTACT == true).AsEnumerable();
    var peopleCollection = new EntityCollection<t_PEOPLE>();
    foreach (var m in PeopleQuery)
    {
        //This is problem.-----------
        peopleCollection.Add(m);
    }    //--------------
    BusinessQuery.t_PEOPLE = peopleCollection;    
    return PartialView("_EditBusiness", BusinessQuery);
    }                    
    return RedirectToAction("Index");              
}

public t_BUSINESS GetBusinessById(int id){
    if (id == 0)
        return null;
    var query = from b in db.t_BUSINESS
                where b.BS_KEY == id
                select b;
    var Business = query.FirstOrDefault();
    return Business;
}

如何将PeopleQuery分配给BusinessQuery.t_PEOPLE

出现错误,显示

The object could not be added to the EntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object

如何在c# MVC中分配部分视图数据给模型

您可以直接查询您要查找的记录:

public ActionResult BusinessDetails()
{               
    int bsId = bskey ?? default(int);
    var business = GetContactBusinessById(bsId);    
    return PartialView("_EditBusiness", business);
}
public t_BUSINESS GetContactBusinessById(int id)
{
    if (id == 0)
    {
        return null;
    }
    var query = 
        from b in db.t_BUSINESS
        from p in b.t_PEOPLE
        where b.BS_KEY == id && p.PP_IS_CONTACT
        select b;
    return query.FirstOrDefault();
}

try this

var PeopleQuery = BusinessQuery.t_PEOPLE.Where(p => p.PP_IS_CONTACT == true).ToList();