如何在编辑模型时传递对象(其他模型)?
假设我的数据库中有公司模型。它与License和UserProfile表具有一对多的关系:
public class Company
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public int Role { get; set; }
public virtual ICollection<License> Licenses { get; set; }
public virtual ICollection<UserProfile> Users { get; set; }
}
我从下一个方向从数据库中获取我的公司(我包括许可证和用户):
Company currentCompany =
db.Companies.Include(c=>c.Licenses).Include(c=>c.Users).FirstOrDefault(c => c.Id == companyId);
现在我的Controller Action看起来像:
public ActionResult EditCompany([Bind(Include = "Id, Name, Country, Role, Licenses, Users")] Company company)
我没有绑定其他值(Id,Name等)的问题。
我应该如何从View传递用户和许可证以使其进入控制器操作?
答案 0 :(得分:0)
您可以创建要发送的数据数组,然后使用AJAX将数组发送到控制器。
在下面的示例中,函数SendData
会将data
发送到HomeController
,动作GetData
。
function SendData() {
var url = "/Home/GetData";
$.ajax({
url: url,
data: { data: data},
cache: false,
type: "POST",
success: function () {
//do smth
},
error: function () {
//do smth else
}
});
}
答案 1 :(得分:0)
<强>解决强>
感谢Henk Holterman和Stepehn Muecke,我们找到了解决方案
就我而言,由于我在编辑公司详细信息时没有更改许可证和用户,我应该这样做:
我的控制器动作现在看起来像这样:
[HttpPost]
[ValidateAntiForgeryToken]
[AuthorizeUserRole(Roles = Roles.PortalAdmin)]
public ActionResult EditCompany([Bind(Include = "Id, Name, Country, Role")] Company company)
{
if (ModelState.IsValid)
{
var getCompanyWithSameName = db.Companies.SingleOrDefault(p => p.Name == company.Name && p.Id != company.Id);
if (getCompanyWithSameName == null)
{
var getCompany = db.Companies.SingleOrDefault(p => p.Id == company.Id);
company.Licenses = getCompany.Licenses;
company.Users = getCompany.Users;
db.Set<Company>().AddOrUpdate(company);
db.SaveChanges();
return RedirectToAction("CompanyIndex", "Admin", new{ companyId = company.Id});
}
ModelState.AddModelError("", "Company with this name already exists: " + company.Name);
return View(company);
}
ModelState.AddModelError("", "An error occured. Please Try again");
return View(company);
}