MVC3中View和PartialView的模型相同

本文关键字:模型 PartialView View MVC3 | 更新日期: 2023-09-27 18:02:59

我有2个功能加载和编辑。记录加载在WebGrid和编辑,我使用弹出式。但对于这两个功能,我使用相同的模型。这就是我得到错误的地方。

当记录加载它工作正常,当我使用编辑它工作正常,但当我试图保存编辑并返回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的过程是正确的。我必须创建一个单独的model编辑?例如,如果我在我的应用程序中有一些15个编辑功能,那么我必须创建30个模型?

请帮助。

MVC3中View和PartialView的模型相同

在编辑局部视图中,你没有一个性别下拉菜单,所以当模型绑定发生在控制器方法上时,性别总是会是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;