我正在粘贴c#控件下面的代码段。我无法弄清楚的是我正在进入AddPerson的formViewModel是否已正确填充,但是当我在下面调用RedirectToAction到“SaveForm”方法并且我传递了formViewModel时,它将为空“ SaveForm“方法。
关于我不理解的任何建议?
谢谢,
[HttpPost]
public IActionResult AddPerson(GikFormViewModel formViewModel)
{
if(formViewModel.Items == null)
{
//formViewModel.Items.Add(new GikItemViewModel() { })
formViewModel.Items = new List<GikItemViewModel>();
}
if (!ModelState.IsValid)
{
return View("Index", formViewModel);
}
// REDIRECTING HERE TO "SaveForm" Formatting is not properly done
return RedirectToAction("SaveForm", formViewModel);
//return View("Index", formViewModel);
}
public IActionResult SaveForm(GikFormViewModel formViewModel)
{
var person = formViewModel.Person;
var items = formViewModel.Items;
var gikItems = new Collection<Gikitem>();
//var gikPerson = new Gikperson();
//var gikItem = new Gikitem();
var gikPerson = new Gikperson()
{
Organization = person.Organization,
Title = person.Title,
Name = person.FirstName + " " + person.LastName,
AddressLineOne = person.AddressLineOne,
AddressLineTwo = person.AddressLineTwo == null ? null : person.AddressLineTwo,
City = person.City,
State = person.State,
Zipcode = person.Zipcode,
Phone = person.Phone,
DoNoContact = person.DoNotContact == true ? 1 : 2,
Email = person.Email
};
答案 0 :(得分:1)
尝试使用TempData。
ASP.NET MVC中的TempData可用于存储可在后续请求中使用的临时数据。完成后续请求后,TempData将被清除。
AddPerson操作
[HttpPost]
public IActionResult AddPerson(GikFormViewModel formViewModel)
{
if(formViewModel.Items == null)
{
//formViewModel.Items.Add(new GikItemViewModel() { })
formViewModel.Items = new List<GikItemViewModel>();
}
if (!ModelState.IsValid)
{
return View("Index", formViewModel);
}
//Save the model into the TempData object.
TempData["model] = formViewModel;
return RedirectToAction("SaveForm");
//return View("Index", formViewModel);
}
SaveForm操作
public IActionResult SaveForm()
{
//If TempData doesn't contains your model then return error message or something.
if(!TempData.ContainsKey("model"))
return new HttpNotFoundResult();
//Retrieve the model from TempData object.
var formViewModel = TempData["model"] as GikFormViewModel;
var person = formViewModel.Person;
var items = formViewModel.Items;
var gikItems = new Collection<Gikitem>();
...
}