我从formcollectionn获取数据并将其存储到列表中我的问题现在是我的context.saveshange是不是将数据保存到地址数据库中我的上下文保存后是0?我真的不知道我的问题是因为先使用sql建立我的实体框架?
public class AddressController : Controller
{
private readonly CustomersDBEntities context = new CustomersDBEntities();
//
// GET: /Address/
public ActionResult Index()
{
return View();
}
//
// GET: /Address/Welcome/
public string Welcome()
{
return "This is the Welcome action method...";
}
[HttpPost]
public ActionResult Create(Address address)
{
//Loop through the request.forms
var Addesslist = new List<Address>();
for (int i = 1; i <= Request.Form.Count; i++)
{
var street = Request.Form["street_0" + i + ""];
var city = Request.Form["city_0" + i + ""];
var postalCode = Request.Form["postalCode_0" + i + ""];
var province = Request.Form["province_0" + i + ""];
var personID = 1;
if (street != null && city != null && postalCode != null && province != null)
{
Addesslist.Add(new Address { Street = street, City = city, Province = province, PostalCode = postalCode, PersonID = personID });
Addesslist.ForEach(p => context.SaveChanges());
if (context.SaveChanges() == Addesslist.Count)
{
return RedirectToAction("Index");
}
else
{
//Redirect to an error page or
}
}
else
{
break;
}
}
return RedirectToAction("Index");
}
}
}
答案 0 :(得分:0)
您可以使用此代码段使其正常工作
[HttpPost]
public ActionResult Create(Address address)
{
//Loop through the request.forms
var Addesslist = new List<Address>();
for (int i = 1; i <= Request.Form.Count; i++)
{
var street = Request.Form["street_0" + i + ""];
var city = Request.Form["city_0" + i + ""];
var postalCode = Request.Form["postalCode_0" + i + ""];
var province = Request.Form["province_0" + i + ""];
var personID = 1;
if (street != null && city != null && postalCode != null && province != null)
{
try
{
context.Addresses.Add(new Address
{
Street = street,
City = city,
Province = province,
PostalCode = postalCode,
PersonID = personID
});
context.SaveChanges();
}
catch (Exception exc)
{
}
}
else
{
break;
}
}
return RedirectToAction("Index");
}