[英]Same model for View and PartialView in MVC3
我有2個功能加載和編輯。 記錄被加載到WebGrid
並使用彈出窗口進行編輯。 但是對於這兩個功能,我使用的是同一模型。 這就是我出錯的地方。
當記錄被加載時,它工作正常,當我使用edit時,它工作正常,但是當我嘗試保存編輯並返回model
,出現錯誤。
// MainView
@model AdhiaRecruitment.Models.CandidateDetailsModel
@{
ViewBag.Title = "CandidateDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
<style type="text/css">
.grid
{
width: 100%;
}
</style>
}
<h2>
CandidateDetails</h2>
<div style="padding: 7px 0;">
<input type="button" value="Add New Product" onclick="OpenCreatePopup()" />
</div>
<div style="width: 100%;">
@{
string template = string.Format("<text><img src='/img/edit.png' title='Edit' onclick='EditProduct({0})' /><img src='/img/delete.png' title='Delete' onclick='DeleteProduct({0})' /></text>", Model.CDId);
WebGrid grid = new WebGrid(Model.LoadAllCandidateDetails());
@grid.GetHtml(
tableStyle: "grid",
fillEmptyRows: false,
headerStyle: "gvHeading",
alternatingRowStyle: "gvAlternateRow",
rowStyle: "gvRow",
footerStyle: "gvFooter",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("CDId", "ID"),
grid.Column("Name", "Name"),
grid.Column("Gender", "Gender"),
grid.Column("", header: "Actions", canSort:false,
format: @<text>
@Html.Raw("<img src='/Images/edit-icon.png' alt='Edit' title='Edit' onclick='EditProduct(" + item.CDId + ")' />")
@Html.Raw("<img src='/Images/delete-icon.png' alt='Delete' title='Delete' onclick='DeleteProduct(" + item.CDId + ")' />")
</text>
)
})
}
</div>
<div id="DivToAppendPartialView">
</div>
<script type="text/javascript">
var ph = $("#DivToAppendPartialView");
ph.dialog({
modal: true,
width: 560,
height: 560,
title: "Edit Candidate",
resizable: false,
autoOpen: false
});
function EditProduct(cid) {
ph.load("/CandidateDetails/EditCandidateDetails?candidateid=" + cid, function () {
ph.dialog('open');
});
}
</script>
//編輯視圖
@model AdhiaRecruitment.Models.CandidateDetailsModel
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>CandidateDetailsModel</legend>
<div class="editor-label">
@* # @Html.DisplayFor(model => model.CDId)*@
@Html.EditorFor(model => model.CDId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.Gender, Model.GenderList(),"--Select--")
@Html.ValidationMessageFor(x => x.Gender, "Gender field is required")
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
//模型
public class CandidateDetailsModel
{
public int CDId { get; set; }
[Required(ErrorMessage = "Please provide name!")]
[StringLength(50, ErrorMessage = "Name is too long!")]
[Display(Name = "Name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please select gender!")]
[Display(Name = "Gender")]
public string Gender { get; set; }
public SelectList GenderList()
{
List<SelectListItem> lstGender = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Male" },
new SelectListItem { Value = "2", Text = "Female" },
};
var selected = lstGender.Where(x => x.Text == Gender).First();
Gender = selected.Value;
return new SelectList(lstGender, "Value", "Text", Gender);
}
public List<CandidateDetails> LoadAllCandidateDetails()
{
List<CandidateDetails> lstCandidateDetails = new List<CandidateDetails>();
CandidateServiceClient csClient = new CandidateServiceClient();
lstCandidateDetails = csClient.LoadAllCandidateDetails();
return lstCandidateDetails;
}
public int SaveCandidateDetails(CandidateDetails cdDetails)
{
int result = 0;
CandidateServiceClient csClient = new CandidateServiceClient();
result = csClient.SaveCandidateDetails(cdDetails);
return result;
}
//控制器
public class CandidateDetailsController : Controller
{
//
// GET: /Candidate/
public ActionResult CandidateDetails()
{
return View(new CandidateDetailsModel());
}
[HttpGet]
public PartialViewResult EditCandidateDetails(int candidateId)
{
CandidateDetailsModel cdSingle = new CandidateDetailsModel();
CandidateDetails cdModel = cdSingle.LoadAllCandidateDetails().Where(x => x.CDId == candidateId).FirstOrDefault();
cdSingle.CDId = cdModel.CDId;
cdSingle.Name = cdModel.Name;
cdSingle.Gender = cdModel.Gender;
return PartialView(cdSingle);
}
[HttpPost]
public ViewResult EditCandidateDetails(CandidateDetails cdDTO)
{
CandidateDetailsModel cdModel = new CandidateDetailsModel();
CandidateDetails cdSingle = new CandidateDetails();
cdSingle.CDId = cdDTO.CDId;
cdSingle.Name = cdDTO.Name;
cdSingle.Gender = cdDTO.Gender;
cdModel.SaveCandidateDetails(cdSingle);
return View(cdModel);
}
}
單擊保存后,將加載model
,並且在加載GenderList
時,將拋出null錯誤。
我不確定我編寫的MVC
程序是否正確。 我是否需要為Edit創建一個單獨的model
? 如果是,例如,如果我的應用程序中有15種編輯功能,那么我必須創建30個模型?
請幫助。
在您的Edit Partial View中,您沒有性別下拉菜單,因此當Controller方法上發生模型綁定時,性別將始終為null
。
如果您不希望用戶更改/編輯性別,則可以使用隱藏字段將當前性別發送回服務器。
@Html.HiddenFor(model => model.Gender)
如果要使性別可編輯,則需要一個下拉菜單。
@Html.DropDownListFor(model => model.Gender, Model.GenderList())
編輯:要解決null性別問題,只需將null檢查並默認設置為:
Gender = Gender == null ? "male" : Gender; //Set default if null
var selected = lstGender.Where(x => x.Text == Gender).First();
Gender = selected.Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.