2014-01-15 24 views
1

我正在爲註冊用戶的個人數據和工作體驗製作表單。 MVC5。更新部分查看錶單內容清理

我有一個由客戶端和JobExperiences實體,與EF代碼第一

在這個模型中,我創建的ViewModels,這樣創建的模型。

的jobExperience視圖模型

public class JobExperienceViewModel 
{ 
    [Required] 
    [Display(Name = "Nombre Compañia")] 
    public string CompanyName { get; set; } 

    [Required] 
    [Display(Name = "Fecha de Ingreso")] 
    [DataType(DataType.Date)] 
    public DateTime EntryDate { get; set; } 

    [Required] 
    [Display(Name = "Fecha de Retiro")] 
    [DataType(DataType.Date)] 
    public DateTime RetirementDate { get; set; } 


    [Required] 
    [Display(Name = "Cargo")] 
    public string Role { get; set; } 

    [Required] 
    [Display(Name = "Funciones")] 
    public string Functions { get; set; } 

    [Required] 
    [Display(Name = "Motivo de Retiro")] 
    public string RetirementCause { get; set; } 
} 

保存的個人資料和工作經驗,像這樣 公共類ResumeViewModel簡歷視圖模型 {

public ResumeViewModel(Client client, ApplicationUser user) 
    { 
     ... 
    } 


    public List<JobExperienceViewModel> JobExperienceViewModels { get; set; } 

    [Display(Name = "Primer nombre")] 
    public string FirstName { get; set; } 

    [Display(Name = "Segundo nombre")] 
    public string MiddleName { get; set; } 

    [Display(Name = "Primer apellido")] 
    public string LastName { get; set; } 
} 

我創建了一個簡歷控制器管理所有這些數據

public class ResumeController : Controller 
{ 
    #region Global Actions 

    // 
    // GET: /Resume/ 
    //This method loads the information for a given userName and loads the viewmodel and pass it to the view 
    [Authorize(Roles = "Admin, Recepcionista, Orientador")] 
    public ActionResult Index(string userName) 
    { 
     var context = new ApplicationDbContext(); 
     var user = (from _user in context.Users 
        where _user.UserName == userName 
        select _user).FirstOrDefault(); 

     Client client = new Client(); 
     try 
     { 
      client = (from _client in context.Client 
         where _client.ApplicationUserId == user.Id 
         select _client).FirstOrDefault(); 

     } 
     catch (System.Reflection.TargetException) 
     { 
      client = new Client(); 
     } 

     ResumeViewModel model; 

     model = new ResumeViewModel(client, user); 

     TempData["ResumeViewModel"] = model; 
     return View(model); 
    } 

    //This method is inttended to save all resume data to persistence 
    [HttpPost] 
    public ActionResult Index(ResumeViewModel model) 
    { 
     ApplicationDbContext context = new ApplicationDbContext(); 
     bool exists = false; 

     var client = (from _client in context.Client 
         where _client.ApplicationUserId == model.ApplicationUserId 
         select _client).FirstOrDefault(); 

     if (!String.IsNullOrEmpty(client.ApplicationUserId)) 
     { 
      exists = true; 
     } 

     client.Address = model.Address; 
     client.ArmyCard = model.ArmyCard; 
     client.ArmyCardClass = model.ArmyCardClass; 
     client.BasicKnowledgeCoreId = model.SelectedBasicKnowledgeCoreId; 
     client.BirthCityId = model.SelectedBirthCityId; 
     client.BirthCountryId = model.SelectedBirthCountryId; 
     client.BirthDate = model.BirthDate; 
     client.BirthDepartmentId = model.SelectedBirthDepartmentId; 
     client.CellPhoneNumber = model.CellPhoneNumber; 
     client.Comments = model.Comments; 
     client.DataVisibilityLevelId = model.SelectedDataVisibilityLevelId; 
     client.DocumentNumber = model.DocumentNumber; 
     client.DocumentTypeId = model.SelectedDocumentTypeId; 
     client.DrivingLicenceExpirationDate = model.DrivingLicenceExpirationDate; 
     client.DrivingLicenseCategoryId = model.SelectedDrivingLicenseCategoryId; 
     client.EducationCountryId = model.SelectedEducationCountryId; 
     client.FirstNationalityId = model.SelectedFirstNationalityId; 
     client.GenreID = model.SelectedGenreId; 
     client.GraduationYear = model.GraduationYear; 
     client.HandicapTypeID = model.SelectedHandicapTypeID; 
     client.HasWorkExperience = model.HasWorkExperience; 
     client.HireTypeId = model.SelectedHireTypeId; 
     client.HomeCityId = model.SelectedHomeCityId; 
     client.HomeCountryId = model.SelectedHomeCountryId; 
     client.HomeDepartmentId = model.SelectedHomeDepartmentId; 
     client.Institution = model.Institution; 
     client.IsGraduated = model.IsGraduated; 
     client.IsHomeOfficeInterested = model.IsHomeOfficeInterested; 
     client.IsHouseHoldHead = model.IsHouseHoldHead; 
     client.LanguageId = model.SelectedLanguageId; 
     client.LanguageSkillLevelID = model.SelectedLanguageSkillLevelID; 
     client.MarriageStatusId = model.SelectedMarriageStatusId; 
     client.Neighborhood = model.Neighborhood; 
     client.PhoneNumber = model.PhoneNumber; 
     client.ProCardExpeditionDate = model.ProCardExpeditionDate; 
     client.ProCardNumber = model.ProCardNumber; 
     client.ProfessionalCardCareer = model.ProfessionalCardCareer; 
     client.ProfessionalProfile = model.ProfessionalProfile; 
     client.SalaryRangeId = model.SelectedSalaryRangeId; 
     //Este campo está comentadoporque el proceso de registro debe hacerse por detalles del nivel, donde esta elid y sus detalles. 
     //client.ScholarLevelId = model.SelectedScholarLevelId; 
     client.SecondNationalityId = model.SelectedSecondNationalityId; 
     client.Title = model.Title; 
     client.WorkStatusID = model.SelectedWorkStatusID; 



     if (!exists) 
     { context.Client.Add(client); } 

     try 
     { 
      if (context.SaveChanges() > 0) 
       RedirectToAction("Index", "SearchClient"); 
      else { return View(model); } 
     } 
     catch (Exception) 
     { 
      return View(model); 
      throw; 
     } 

     return View(model); 
    } 

    #endregion 

    #region JobExperience 


    public ActionResult ShowJobExperience(ICollection<Models.JobExperienceViewModel> JobExperienceViewModels) 
    { 
     return View(JobExperienceViewModels); 
    } 

    public ActionResult CreateJobExperience(ICollection<Models.JobExperienceViewModel> JobExperienceViewModels) 
    { 
     return View(JobExperienceViewModels); 
    } 

    [HttpGet] 
    public ActionResult CreateJobExperience(Models.JobExperienceViewModel JobExperienceViewModel) 
    { 
     #region Using TempData 

     ResumeViewModel model = (ResumeViewModel)TempData["ResumeViewModel"]; 

     model.JobExperienceViewModels.Add(JobExperienceViewModel); 

     TempData["ResumeViewModel"] = model; 

     #endregion 

     return View("Index", model); 
    } 

    #endregion 
} 

最後,這些視圖按照這種方式組織。一個父視圖,其中包含所有個人數據,以及jobExperiences列表,並在大表單中創建視圖作爲部分視圖。

視圖國稅發一些相關部分是

@model CAEWebSite.Models.ResumeViewModel 

@{ 
    ViewBag.Title = "Hoja de Vida"; 
} 

@using (Ajax.BeginForm(null)) 
{ 
@Html.AntiForgeryToken() 

<div class="form-horizontal"> 
    <h4> 
     @{var fullName = Model.FirstName + 
        (!String.IsNullOrWhiteSpace(Model.MiddleName) ? " " + Model.MiddleName : String.Empty) + 
        (!String.IsNullOrWhiteSpace(Model.LastName) ? " " + Model.LastName : String.Empty) + 
        (!String.IsNullOrWhiteSpace(Model.SecondLastName) ? " " + Model.SecondLastName : String.Empty); 
     } 
     @fullName 
    </h4> 
    <hr /> 
    @Html.ValidationSummary(true) 

    <div class="form-group"> 
     <div class="col-md-12"> 
      @Model.Email 
     </div> 
    </div> 

    <div class="form-group"> 
     <div class="col-md-12"> 
      @Model.UserName 
     </div> 
    </div> 
    <hr /> 
    <h3>Datos personales</h3> 
    <div class="form-group"> 
     @Html.LabelFor(model => model.BirthDate, new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.TextBoxFor(model => model.BirthDate, new { @type = "date" }) 

      @Html.ValidationMessageFor(model => model.BirthDate) 
     </div> 
    </div> 

    <h3>Experiencia laboral</h3> 
    <div class="form-group"> 
     @Html.LabelFor(model => model.HasWorkExperience, new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.EditorFor(model => model.HasWorkExperience) 
      @Html.ValidationMessageFor(model => model.HasWorkExperience) 
     </div> 
    </div> 
    <h3>Trabajos anteriores</h3> 
    <div class="col-md-12"> 
     <div id="divListJobExperience"> 
      @Html.Partial("_ListJobExperience", Model.JobExperienceViewModels) 
     </div> 
     <p> 
      @*@Html.Action("ShowJobExperience", Model.JobExperienceViewModels)*@ 
      <a href="#" onclick="$('#newJobExperience').bPopup({}); return false;">Nueva experiencia</a> 
     </p> 
    </div> 

<div class="form-group"> 
     <div class="col-md-offset-2 col-md-10"> 
      <input type="submit" value="Create" class="btn btn-default" /> 
     </div> 
    </div> 
</div> 

}

<div id="newJobExperience" style="background-color:#fff; border-radius:5px;"> 
<div class="col-md-12"> 
    @Html.Partial("_CreateJobExperience", new CAEWebSite.Models.JobExperienceViewModel()) 
</div> 
</div> 

</div> 

@section Scripts { 
@Scripts.Render("~/bundles/jqueryval") 

<script> 
    $("#newJobExperience").hide(); 
    $("#newRelative").hide(); 
    $("#newCapacitationCourse").hide(); 
    $("#newScholarLevelDetail").hide(); 
</script> 

}

的 @ Html.Partial( 「_ CreateJobExperience」,新CAEWebSite.Models.JobExperienceViewModel())

部分視圖加載了bpopup plu杜松子酒作爲一種情態。部分觀點是這樣的

_ListJobExperience視圖

@model IEnumerable<CAEWebSite.Models.JobExperienceViewModel> 


<table class="table"> 
<tr> 
    <th> 
     @Html.DisplayNameFor(model => model.CompanyName) 
    </th> 
    <th> 
     @Html.DisplayNameFor(model => model.EntryDate) 
    </th> 
    <th> 
     @Html.DisplayNameFor(model => model.RetirementDate) 
    </th> 
    <th> 
     @Html.DisplayNameFor(model => model.Role) 
    </th> 
    <th> 
     @Html.DisplayNameFor(model => model.Functions) 
    </th> 
    <th> 
     @Html.DisplayNameFor(model => model.RetirementCause) 
    </th> 
    <th></th> 
</tr> 

@foreach (var item in Model) 
{ 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.CompanyName) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.EntryDate) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.RetirementDate) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Role) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Functions) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.RetirementCause) 
     </td> 
     <td> 
      @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) | 
      @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) | 
      @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ }) 
     </td> 
    </tr> 
} 

</table> 

_CreateJobExperience查看

public class ResumeController : Controller 
{ 
    #region Global Actions 

    // 
    // GET: /Resume/ 
    [Authorize(Roles = "Admin, Recepcionista, Orientador")] 
    public ActionResult Index(string userName) 
    { 
     var context = new ApplicationDbContext(); 
     var user = (from _user in context.Users 
        where _user.UserName == userName 
        select _user).FirstOrDefault(); 

     Client client = new Client(); 
     try 
     { 
      client = (from _client in context.Client 
         where _client.ApplicationUserId == user.Id 
         select _client).FirstOrDefault(); 

     } 
     catch (System.Reflection.TargetException) 
     { 
      client = new Client(); 
     } 

     ResumeViewModel model; 

     model = new ResumeViewModel(client, user); 

     TempData["ResumeViewModel"] = model; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(ResumeViewModel model) 
    { 
     ApplicationDbContext context = new ApplicationDbContext(); 
     bool exists = false; 

     var client = (from _client in context.Client 
         where _client.ApplicationUserId == model.ApplicationUserId 
         select _client).FirstOrDefault(); 

     if (!String.IsNullOrEmpty(client.ApplicationUserId)) 
     { 
      exists = true; 
     } 

     client.Address = model.Address; 
     client.ArmyCard = model.ArmyCard; 
     client.ArmyCardClass = model.ArmyCardClass; 
     client.BasicKnowledgeCoreId = model.SelectedBasicKnowledgeCoreId; 
     client.BirthCityId = model.SelectedBirthCityId; 
     client.BirthCountryId = model.SelectedBirthCountryId; 
     client.BirthDate = model.BirthDate; 
     client.BirthDepartmentId = model.SelectedBirthDepartmentId; 
     client.CellPhoneNumber = model.CellPhoneNumber; 
     client.Comments = model.Comments; 
     client.DataVisibilityLevelId = model.SelectedDataVisibilityLevelId; 
     client.DocumentNumber = model.DocumentNumber; 
     client.DocumentTypeId = model.SelectedDocumentTypeId; 
     client.DrivingLicenceExpirationDate = model.DrivingLicenceExpirationDate; 
     client.DrivingLicenseCategoryId = model.SelectedDrivingLicenseCategoryId; 
     client.EducationCountryId = model.SelectedEducationCountryId; 
     client.FirstNationalityId = model.SelectedFirstNationalityId; 
     client.GenreID = model.SelectedGenreId; 
     client.GraduationYear = model.GraduationYear; 
     client.HandicapTypeID = model.SelectedHandicapTypeID; 
     client.HasWorkExperience = model.HasWorkExperience; 
     client.HireTypeId = model.SelectedHireTypeId; 
     client.HomeCityId = model.SelectedHomeCityId; 
     client.HomeCountryId = model.SelectedHomeCountryId; 
     client.HomeDepartmentId = model.SelectedHomeDepartmentId; 
     client.Institution = model.Institution; 
     client.IsGraduated = model.IsGraduated; 
     client.IsHomeOfficeInterested = model.IsHomeOfficeInterested; 
     client.IsHouseHoldHead = model.IsHouseHoldHead; 
     client.LanguageId = model.SelectedLanguageId; 
     client.LanguageSkillLevelID = model.SelectedLanguageSkillLevelID; 
     client.MarriageStatusId = model.SelectedMarriageStatusId; 
     client.Neighborhood = model.Neighborhood; 
     client.PhoneNumber = model.PhoneNumber; 
     client.ProCardExpeditionDate = model.ProCardExpeditionDate; 
     client.ProCardNumber = model.ProCardNumber; 
     client.ProfessionalCardCareer = model.ProfessionalCardCareer; 
     client.ProfessionalProfile = model.ProfessionalProfile; 
     client.SalaryRangeId = model.SelectedSalaryRangeId; 
     //Este campo está comentadoporque el proceso de registro debe hacerse por detalles del nivel, donde esta elid y sus detalles. 
     //client.ScholarLevelId = model.SelectedScholarLevelId; 
     client.SecondNationalityId = model.SelectedSecondNationalityId; 
     client.Title = model.Title; 
     client.WorkStatusID = model.SelectedWorkStatusID; 



     if (!exists) 
     { context.Client.Add(client); } 

     try 
     { 
      if (context.SaveChanges() > 0) 
       RedirectToAction("Index", "SearchClient"); 
      else { return View(model); } 
     } 
     catch (Exception) 
     { 
      return View(model); 
      throw; 
     } 

     return View(model); 
    } 

    #endregion 

    #region JobExperience 


    public ActionResult ShowJobExperience(ICollection<Models.JobExperienceViewModel> JobExperienceViewModels) 
    { 
     return View(JobExperienceViewModels); 
    } 

    public ActionResult CreateJobExperience(ICollection<Models.JobExperienceViewModel> JobExperienceViewModels) 
    { 
     return View(JobExperienceViewModels); 
    } 

    [HttpPost] 
    public ActionResult CreateJobExperience(Models.JobExperienceViewModel JobExperienceViewModel) 
    { 
     #region Using TempData 

     ResumeViewModel model = (ResumeViewModel)TempData["ResumeViewModel"]; 

     model.JobExperienceViewModels.Add(JobExperienceViewModel); 

     TempData["ResumeViewModel"] = model; 

     #endregion 

     return View("Index", model); 
    } 

    #endregion 
} 
} 

問題

每當我創建Iupdate的viemodel添加jobExperienceViewModel到一個新的工作經驗體驗列表,並將其發送回視圖以返回。

它的工作原理,經驗列表顯示爲填充。但是,表單中的所有數據都已丟失,清理完畢。

我正在使用在所有用戶交互過程中保持viewmodel狀態的方法,直到他或她在將所有模型發送到持久性時單擊表單提交爲止。

我想我需要的是一種更新體驗列表的方式,就像它在一個老式的UpdatePanel中一樣。

或解決方案,讓我覆蓋的功能。

回答

1

在這裏,你會使用一個Ajax的形式在 「主表」 提交LABORAL expiences不乾淨的數據:

型號:

public class HojaDeVida 
{ 
    public HojaDeVida() 
    { 
     ExperienciasLaborales = new List<ExperienciaLaboral>(); 
    } 

    public string Nombre { get; set; } 
    public string Apellido { get; set; } 
    public IList<ExperienciaLaboral> ExperienciasLaborales { get; set; } 
} 

public class ExperienciaLaboral 
{ 
    public string Empresa { get; set; } 
    public int Anios { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    [HttpGet] 
    public ActionResult Index() 
    { 
     TempData["hojavida"] = new HojaDeVida(); 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(HojaDeVida hojaDeVida) 
    { 
     //Submit the info in "hojaDeVida" and TempData["HojaVida"] 
     return new EmptyResult(); 
    } 

    [HttpPost] 
    public PartialViewResult AddExperienciaLaboral(ExperienciaLaboral experiencia) 
    { 
     var hojadevida = (HojaDeVida)TempData["hojavida"]; 
     hojadevida.ExperienciasLaborales.Add(experiencia); 
     TempData["hojavida"] = hojadevida; 
     return PartialView("_ListExperiencias", hojadevida.ExperienciasLaborales); 
    } 
} 

「校長View「(Hoja de Vida):

@using WebApplication1.Controllers 
@model HojaDeVida 
@{ 
    ViewBag.Title = "Home Page"; 
} 

@using (Html.BeginForm("Index", "Home")) 
    { 
     <div> 
      @Html.LabelFor(x => x.Nombre) 
      @Html.EditorFor(x => x.Nombre) 
     </div> 
     <div> 
      @Html.LabelFor(x => x.Apellido) 
      @Html.EditorFor(x => x.Apellido) 
     </div> 
     <input type="submit" value="Guardar Hoja de Vida" /> 
    } 

@Html.Partial("_AddExperiencia", new ExperienciaLaboral()) 

@section scripts 
{ 
    @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js") 
} 

那麼 「_AddExperience」 PartialView,與Ajax表格:

@using WebApplication1.Controllers 
@model ExperienciaLaboral 
@using (Ajax.BeginForm("AddExperienciaLaboral", "Home", new AjaxOptions { UpdateTargetId = "data", HttpMethod = "POST" })) 
    { 
     <div> 
      @Html.LabelFor(x => Model.Empresa) 
      @Html.EditorFor(x => Model.Empresa) 
     </div> 
     <div> 
      @Html.LabelFor(x => Model.Anios) 
      @Html.EditorFor(x => Model.Anios) 
     </div> 
     <input type="submit" value="Agregar Experiencia" /> 
    } 
<div id="data"> 
    @Html.Partial("_ListExperiencias", new List<ExperienciaLaboral>()) 
</div> 

最後的 「_ListExperiencias」 PartialView:

@model IList<WebApplication1.Controllers.ExperienciaLaboral> 
@foreach (var item in Model) 
    { 
     <div> 
      @string.Format("Empresa : {0} | Años: {1}", item.Empresa, item.Anios) 
    </div> 
    } 

正如你所看到的,Ajax的形式是HTML表單以外,you can't nested two forms(這裏是Ajax表單和HTML表單)而不是你需要使用一些JavaScript或jQuery.Ajax有一個很好的視覺形式嵌套

+0

我無法使它工作,它打開在瀏覽器中單獨部分視圖,而不在我正在處理的頁面中 –

+0

您需要安裝[jquery.unobtrusive-ajax.min.js](https://www.nuget.org/packages/Microsoft.jQuery .Unobtrusive.Ajax /)來自NuGet – Nicolocodev

0

您可以使用ajax + web api或控制器中的任何操作來保存經驗。

+0

你能開發多一點嗎?我試着對控制器進行ajax調用,但是出現了這個錯誤,因爲,誰知道爲什麼,系統試圖找到一個CreateJobExperience視圖,這個視圖不存在,這是一個名爲_CreateJobExperience的局部視圖 –