我有数据进入模型,我想获取表单上的数据发布所有模型都被正常发布,除了模型中的类类型列表被发布为空。
我知道我在渲染时做错了但无法解决它。
以下是我正在渲染的视图中的块:
@model InovaClassic.Models.RegisterModel
<table>
@if (Model.PostReq != null && Model.PostReq._questions != null && Model.PostReq._questions.Count > 0)
{
for (int i = 0; i < Model.PostReq._questions.Count; i++)
{
if (i == 0)
{
<legend style="border-bottom: 1px solid gray; font-size: 16px;">Questions</legend>
}
<tr>
<td>
@Html.Label(Model.PostReq._questions[i].Title)
@Html.HiddenFor(c => c.PostReq._questions[i].Id)
@Html.HiddenFor(c => c.PostReq._questions[i].QuestionnaireId)
</td>
<td>
<textarea name="Answer[@i]" class="required" style="width:520px;height:20px;"></textarea>
</td>
</tr>
}
}
</table>
这是我的注册行动:
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Register(RegisterModel model, FormCollection Form)
{
model.PostReq = new PostRequirements();
ViewBag.Token = "";
if (!model.Availability.EndsAfter)
model.Availability.EndsAfterValue = 1;
//model.Resume.UploadedAt = DateTime.Now;
//model.Resume.ApplicationId = 0;
//model.Resume.IsDefault = true;
foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
//DoSomethingWith(error);
}
}
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
int PostId;
int? ApplicationId = null;
string confirmationToken = WebSecurity.CreateUserAndAccount(model.UserName.Trim(), model.Password, new { Email = model.Email }, true);
var roles = (SimpleRoleProvider)Roles.Provider;
roles.AddUsersToRoles(new string[] { model.UserName.Trim() }, new string[] { "applicant" });
Applicant App = new Applicant();
App = Applicant.MapApplicant(model.RegisterVm);
App.UserId = db.Users.FirstOrDefault(c => c.UserName == model.UserName.Trim()).UserId;
db.Applicant.Add(App);
db.SaveChanges();
bool IsNumber = int.TryParse(Form["PostId"],out PostId);
if (IsNumber)
{
ApplicationId = ApplyJob(App.UserId, PostId);
/*if (model.PostReq != null && model.PostReq._questions != null)
{
for (int i = 0; i < model.PostReq._questions.Count; i++)
{
QuestionnaireAnswers answer = new QuestionnaireAnswers();
answer.ApplicationId = ApplicationId;
answer.QuestionId = model.PostReq._questions[i].QuestionnaireId;
answer.Answer = Form["Answer[" + i + "]"].ToString();
db.QuestionnaireAnswers.Add(answer);
}
}*/
if (Form["QuestionsCount"] != null)
{
int Count = Convert.ToInt32(Form["QuestionsCount"]);
for (int i = 0; i < Count; i++)
{
QuestionnaireAnswers answer = new QuestionnaireAnswers();
answer.ApplicationId = ApplicationId;
answer.QuestionId = Convert.ToInt32(Form["QuestionSeqId[" + i + "]"]);
answer.Answer = Form["Answer[" + i + "]"].ToString();
db.QuestionnaireAnswers.Add(answer);
}
}
for (int i = 1; i < Request.Files.Count; i++)
{
string File = SaveDocument(ApplicationId, i);
int TitleIndex = i - 1;
ApplicationDocument applicationDocument = new ApplicationDocument();
applicationDocument.ApplicationId = Convert.ToInt32(ApplicationId);
applicationDocument.DocumentTitle = Form["PostReq._documents[" + TitleIndex + "]"];
applicationDocument.Path = File;
db.ApplicationDocuments.Add(applicationDocument);
}
}
//if (string.IsNullOrWhiteSpace(Form["PostId"].ToString()))
//{
string FileName = SaveResume(App.UserId, Request.Files[0] as HttpPostedFileBase);
if (FileName != "")
{
model.Resume.Path = FileName;
model.Resume.UserId = App.UserId;
model.Resume.UploadedAt = DateTime.Now;
model.Resume.ApplicationId = ApplicationId;
db.Resumes.Add(model.Resume);
}
if (Form["ends"] == "1")
{
model.Availability.DoesNotEnd = true;
model.Availability.EndsBy = false;
model.Availability.EndsAfter = false;
}
if (Form["ends"] == "2")
{
model.Availability.EndsAfter = true;
model.Availability.DoesNotEnd = false;
model.Availability.EndsBy = false;
}
if (Form["ends"] == "3")
{
model.Availability.EndsBy = true;
model.Availability.EndsAfter = false;
model.Availability.DoesNotEnd = false;
}
model.Availability.ApplicationId = ApplicationId;
model.Availability.UserId = App.UserId;
db.Availabilities.Add(model.Availability);
// }
//if (!string.IsNullOrWhiteSpace(Form["PostId"].ToString()))
//{
// string FileName = SaveResume(App.UserId, Request.Files[0] as HttpPostedFileBase);
// if (FileName != "")
// {
// model.Resume.Path = FileName;
// model.Resume.UserId = App.UserId;
// model.Resume.UploadedAt = DateTime.Now;
// model.Resume.ApplicationId = ApplicationId;
// db.Resumes.Add(model.Resume);
// }
// if (Form["ends"] == "1")
// {
// model.Availability.DoesNotEnd = true;
// model.Availability.EndsBy = false;
// model.Availability.EndsAfter = false;
// }
// if (Form["ends"] == "2")
// {
// model.Availability.EndsAfter = true;
// model.Availability.DoesNotEnd = false;
// model.Availability.EndsBy = false;
// }
// if (Form["ends"] == "3")
// {
// model.Availability.EndsBy = true;
// model.Availability.EndsAfter = false;
// model.Availability.DoesNotEnd = false;
// }
// model.Availability.ApplicationId = ApplicationId;
// model.Availability.UserId = App.UserId;
// db.Availabilities.Add(model.Availability);
// for (int i = 0; i < model.PostReq._questions.Count; i++)
// {
// QuestionnaireAnswers answer = new QuestionnaireAnswers();
// answer.ApplicationId = ApplicationId;
// answer.QuestionId = model.PostReq._questions[i].QuestionnaireId;
// answer.Answer = Form["Answer[" + i + "]"].ToString();
// db.QuestionnaireAnswers.Add(answer);
// }
// for (int i = 1; i < Request.Files.Count; i++)
// {
// string File = SaveDocument(ApplicationId, i);
// ApplicationDocument applicationDocument = new ApplicationDocument();
// applicationDocument.ApplicationId = ApplicationId;
// applicationDocument.DocumentTitle = Form["PostReq._documents[" + i + "]"];
// applicationDocument.Path = File;
// db.ApplicationDocuments.Add(applicationDocument);
// }
// //db.SaveChanges();
//}
//Applicant MyApplicant = Applicant.MapApplicant(model.RegisterVm);
//Test Code
//Resume resume = new Resume();
//resume.Title = "CV97";
//resume.IsDefault = true;
//resume.Path = "37_AdLoader[1].htm";
//resume.UserId = App.UserId;
//resume.ApplicationId = null;
//db.Resumes.Add(resume);
db.SaveChanges();
//WebSecurity.Login(model.UserName, model.Password);
string ReturnURL = TempData["ReturnUrl"] == null ? "" : TempData["ReturnUrl"].ToString();
string str_rev = ReturnURL.Reverse().TakeWhile(c => Char.IsDigit(c)).ToString();
CoverLetter Letter = MyHelpers.RegisterLetter();
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
//string url = MyHelpers.GetBaseUrl() + u.Action("ConfirmAccount", "Account", new { id = confirmationToken, user = model.UserName.Trim(), ReturnUrl = ReturnURL });
string url = MyHelpers.GetBaseUrl() + u.Action("ConfirmAccount", "Account", new { id = confirmationToken, user = model.UserName.Trim() });
string link = "<a href=\"" + url + "\" target=\"_blank\">Confirmation Link</a>";
string Body = Letter.Body.Replace("%link%", link);
MyHelpers.SendMail(model.Email, Letter.Subject, Body);
ViewBag.Token = "1";
return RedirectToAction("Result", "Post", new { id = 3 });
//return View();
// return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
List<Country> Countries = db.Country.ToList();
SelectList CountryList = new SelectList(Countries, "Id", "Name", model.RegisterVm.Country);
List<Country> VisaCountries = db.Country.ToList();
SelectList VisaCountryList = new SelectList(VisaCountries, "Id", "Name", model.RegisterVm.VisaCountry);
List<MaritalStatus> MaritalStatuses = db.MaritalStatus.ToList();
SelectList MaritalStatusList = new SelectList(MaritalStatuses, "Id", "Name", model.RegisterVm.MaritalStatus);
List<Title> Titles = db.Title.ToList();
SelectList TitleList = new SelectList(Titles, "Id", "Name", model.RegisterVm.Title);
List<VisaType> VisaTypes = db.VisaType.ToList();
SelectList VisaTypeList = new SelectList(VisaTypes, "Id", "Name", model.RegisterVm.VisaType);
ViewBag.CountryList = CountryList;
ViewBag.VisaCountryList = VisaCountryList;
ViewBag.MaritalStatusList = MaritalStatusList;
ViewBag.TitleList = TitleList;
ViewBag.VisaTypeList = VisaTypeList;
// If we got this far, something failed, redisplay form
//return View(model);
return PartialView("~/Views/Account/RegisterUser.cshtml", model);
}
这是我的模特:
public class RegisterModel
{
[Required(ErrorMessage="Username is required")]
[StringLength(50)]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required(ErrorMessage = "Password is required")]
[StringLength(15, MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Email address is required")]
[DataType(DataType.EmailAddress), RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Please enter a valid email address.")]
[StringLength(100)]
public string Email { get; set; }
public RegisterViewModel RegisterVm { get; set; }
public Resume Resume { get; set; }
public Availability Availability { get; set; }
public PostRequirements PostReq { get; set; }
}
参见PostRequirements:
public class PostRequirements
{
public List<Question> _questions { get; set; }
public List<string> _documents { get; set; }
}
}
答案 0 :(得分:0)
您缺少Form
个标签。
@using (Html.BeginForm())
{ }
这应该包含在表单元素周围。