我正在尝试使用表单向数据库添加一些数据。
我已经有很少的数据并且设法让编辑工作,但是添加了我的问题。
这是我编辑数据库中数据的编辑代码:
[HttpPost]
public ActionResult Save(M2Portal.Areas.Admin.Models.Users.Roles roleForm)
{
try
{
if (ModelState.IsValid)
{
if (Mode == "Add")
{
****This is where my add code goes*******
}
else
{
var role = Srvctx.Roles.FirstOrDefault(w => w.RoleID == roleForm.RoleId);
role.RoleName = roleForm.RoleName;
role.RoleDescription = roleForm.RoleDescription;
Srvctx.SubmitChanges();
}
return RedirectToAction("RoleManagement");
}
return RedirectToAction("RoleManagement");
}
catch (Exception e)
{
return RedirectToAction("RoleManagement");
}
}
这是模型的代码:
这是为了添加。
public Roles()
{
Mode = "Add";
RoleId = 0;
RoleDescription = "";
RoleName = "";
CustomerBlacklist = new List<vw_RoleCustomerBlacklist>();
}
这适用于编辑:有效。
public Roles(int roleId)
{
Mode = "Edit";
//RoleId = roleId;
RoleId = roleId;
RoleName = _m2Sctx.Roles.Where(s => s.RoleID == RoleId).Select(c => c.RoleName).FirstOrDefault();
RoleDescription = _m2Sctx.Roles.Where(s => s.RoleID == RoleId).Select(c => c.RoleDescription).FirstOrDefault();
CustomerBlacklist = _m2Sctx.vw_RoleCustomerBlacklists.Where(s => s.RoleId == roleId).ToList();
CustName = CustName;
}
所以现在我正在使用添加功能,它遇到了问题。
在表单中添加新数据......任何想法:
if (Mode == "Add")
{
****This is where my add code goes*******
}
你可以看到我的编辑是如何设置的,但是为了添加它完全不同,并且有很难对它进行罚款......
答案 0 :(得分:1)
尝试以下代码:
if (ModelState.IsValid)
{
if (roleForm.RoleId == 0)
{
var role = new Role()
{
RoleName = roleForm.RoleName,
RoleDescription = roleForm.RoleDescription
};
Srvctx.Roles.InsertOnSubmit(role);
Srvctx.SubmitChanges();
}
else
{
var role = Srvctx.Roles.FirstOrDefault(w => w.RoleID == roleForm.RoleId);
role.RoleName = roleForm.RoleName;
role.RoleDescription = roleForm.RoleDescription;
Srvctx.SubmitChanges();
}
return RedirectToAction("RoleManagement");
}
答案 1 :(得分:0)
var newRole = new Role {
RoleName = roleForm.RoleName,
RoleDescription = roleForm.RoleDescription
};
Srvctx.Roles.InsertOnSubmit(newRole);
假设你的角色&#34;实体类称为Role
。此外,您还可以填充CustomerBlacklist,如果它是&#34; Role&#34;的一部分。类。
答案 2 :(得分:0)
用于编辑模型而不是
public Roles(int roleId)
{
Mode = "Edit";
//RoleId = roleId;
RoleId = roleId;
RoleName = _m2Sctx.Roles.Where(s => s.RoleID == RoleId).Select(c => c.RoleName).FirstOrDefault();
RoleDescription = _m2Sctx.Roles.Where(s => s.RoleID == RoleId).Select(c => c.RoleDescription).FirstOrDefault();
CustomerBlacklist = _m2Sctx.vw_RoleCustomerBlacklists.Where(s => s.RoleId == roleId).ToList();
CustName = CustName;
}
创建一个基于roleId返回Role的单个对象的方法:
public M2Portal.Areas.Admin.Models.Users.Roles Roles(int roleId)
{
var roleDBEntity = _m2Sctx.Roles.FirstOrDefault(s => s.RoleID == RoleId);
var roleModelEntity = new M2Portal.Areas.Admin.Models.Users.Roles(){
RoleId = roleDBEntity.RoleId,
RoleName = roleDBEntity.RoleName,
RoleDescription = roleDBEntity.RoleDescriptio
CustomerBlacklist = roleDBENtity.CustomerBlacklist // Assuming there's relation between Role and CustomerBlackList table
};
return roleModelEntity;
}