简体   繁体   English

MVC3中的View和PartialView的模型相同

[英]Same model for View and PartialView in MVC3

I am having 2 functionalities Load and Edit. 我有2个功能加载和编辑。 The records are loaded in the WebGrid and for edit i'm using popup. 记录被加载到WebGrid并使用弹出窗口进行编辑。 But for both functions i'm using the same Model. 但是对于这两个功能,我使用的是同一模型。 This is where i'm getting error. 这就是我出错的地方。

When the records are loaded it works fine, when i use edit it works fine, but when i try to save the edits and return the model i'm getting error. 当记录被加载时,它工作正常,当我使用edit时,它工作正常,但是当我尝试保存编辑并返回model ,出现错误。

//MainView // 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>

//Edit View //编辑视图

 @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>

//Model //模型

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;
        }

//Controller //控制器

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);
        }

    }

After clicking save the model is loaded and when the GenderList is loading its throwing me the null error. 单击保存后,将加载model ,并且在加载GenderList时,将抛出null错误。

I'm not sure the process for MVC i have written is right. 我不确定我编写的MVC程序是否正确。 Do i have to create a separate model for Edit? 我是否需要为Edit创建一个单独的model If yes, For example if i have some 15 Edit functionalities in my application then i have to create 30 models?? 如果是,例如,如果我的应用程序中有15种编辑功能,那么我必须创建30个模型?

Kindly help. 请帮助。

In your Edit Partial View you do not have a gender dropdown menu so when model binding happens on the Controller method, gender is always going to be null . 在您的Edit Partial View中,您没有性别下拉菜单,因此当Controller方法上发生模型绑定时,性别将始终为null

If you do not want the user to change/edit gender then you can use a hidden field to send the current gender back to the server. 如果您不希望用户更改/编辑性别,则可以使用隐藏字段将当前性别发送回服务器。

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

If you want to make gender editable then you will need a dropdown menu. 如果要使性别可编辑,则需要一个下拉菜单。

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

EDIT: To solve the null Gender problem just put a null check and default it like so: 编辑:要解决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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM