MVC3中的View和Partial View的相同模型

时间:2014-05-12 13:38:58

标签: c# asp.net-mvc asp.net-mvc-3 razor

我有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正在加载时,它会抛出空错误。

我不确定我写的MVC的过程是否正确。我是否必须为编辑创建单独的model?如果是,例如,如果我的应用程序中有15个编辑功能,那么我必须创建30个模型??

请帮助。

1 个答案:

答案 0 :(得分:0)

在“编辑部分视图”中,您没有性别下拉菜单,因此在Controller方法上发生模型绑定时,性别始终为null

如果您不希望用户更改/编辑性别,则可以使用隐藏字段将当前性别发送回服务器。

@Html.HiddenFor(model => model.Gender)

如果您想要编辑性别,则需要一个下拉菜单。

@Html.DropDownListFor(model => model.Gender, Model.GenderList())

编辑: 要解决null性别问题,只需进行空检查并默认为:

Gender = Gender == null ? "male" : Gender; //Set default if null
var selected = lstGender.Where(x => x.Text == Gender).First();
            Gender = selected.Value;