视图未将正确的信息传递给控制器

发布于 2024-12-13 02:33:37 字数 4188 浏览 0 评论 0原文

也许解决这个问题应该很简单,但我只是找不到问题所在,我必须解释我的场景以便读者理解。

我有一个名为 Position 的类,另一个 Applicant,另一个 ApplicantPosition,另一个 Status 和 ApplicantPositionHistory

该类 Position 包含职位名称等基本信息:例如:.net 开发人员。 Applicant 类保存姓名等基本信息。 ApplicantPosition 类保存关系、上次修改日期和 CURRENTSTATUS。 ApplicantPositionHistory 类有 2 个对状态一的引用,称为 newStatus 和 oldStatus。

public class ApplicationPositionHistory
{


  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ApplicationPositionHistoryID { get; set; }

[ForeignKey("ApplicantPositionID")]
public ApplicantPosition ApplicantPosition { get; set; }

[Column("ApplicantPositionID")]
public int ApplicantPositionID { get; set; }

[Column("OldStatusID")]
public int OldStatusID { get; set; }

[Column("NewStatusID")]
public int NewStatusID { get; set; }

[ForeignKey("OldStatusID")]
public Status OldStatus { get; set; }

[ForeignKey("NewStatusID")]
public Status NewStatus { get; set; }

[StringLength(500, MinimumLength = 3, ErrorMessage = "Comments  should not be longer than 500 characters.")]
[Display(Name = "Comments")]
public string Comments { get; set; }

[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Display(Name = "Date")]
public DateTime DateModified { get; set; }
}

在我的前端,我有一个屏幕显示已申请职位的申请人

name   position            actions
andew   .net developer     view history

When they click on history they see:
old status     new status      comments         datemodified
new            applied         new prospect
applied        approved by hr  approved by hr

在他们创建 ApplicantPositionHistory 实体的屏幕中出现的问题。 我想使用最后一行中的 newStatus 作为 oldstatus,并且 newStatus 应该是用户选择的状态。 (这里是整个问题的关键)

在下面的代码中,newStatus和OldStatus总是指向同一个ID。因此插入有效,但它始终使用相同的 ID,并且不显示对申请人状态历史记录的真实跟踪。

这是 HTML

<table>    
    <tr>
        <th>
            Previous Status
        </th>
    </tr>
    <tr>
        <td>
             @Html.Label(ViewData["oldStatus"].ToString())
        </td>
    </tr>
</table>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ApplicationPositionHistory</legend>       
        <div class="editor-label">
            New Status
        </div>
        <div class="editor-field">
            @Html.DropDownList("NewStatusID", (IEnumerable<SelectListItem>)ViewBag.Statuses)
            @Html.ValidationMessageFor(model => model.NewStatusID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Comments)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Comments)
            @Html.ValidationMessageFor(model => model.Comments)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

这是控制器操作

[HttpPost]
        public ActionResult Create(ApplicationPositionHistory applicationpositionhistory)
        {
            applicationpositionhistory.DateModified = DateTime.Now;

            if (ModelState.IsValid)
            {
                applicationpositionhistory.OldStatusID = applicationpositionhistory.NewStatusID;
                applicationpositionhistory.OldStatus =
                    _unitOfWork.StatusRepository.GetStatusById(applicationpositionhistory.NewStatusID);

                _unitOfWork.ApplicantPositionHistoryRepository.InsertApplicationPositionHistory(applicationpositionhistory);
                _unitOfWork.Save();
                return RedirectToAction("History", new { applicantPositionID = ViewData["applicantPositionId"] });  
            }

            ViewBag.oldStatusID = new SelectList(_unitOfWork.StatusRepository.GetAllStatus(), "StatusID", "status", applicationpositionhistory.OldStatusID);
            ViewBag.newStatusID = new SelectList(_unitOfWork.StatusRepository.GetAllStatus(), "StatusID", "status", applicationpositionhistory.NewStatusID);
            return View(applicationpositionhistory);
        }

Probably the fix of this should be something simple, but I just cant find whats wrong and I have to explain my scenario in order for readers to understand.

I have a Class called Position, another Applicant, Another ApplicantPosition, another Status and ApplicantPositionHistory

The class Position holds basic info like position name: eg: .net developer.
The class Applicant holds basic info like name, first name,etc.
The class ApplicantPosition holds the relationship, last modified date and CURRENTSTATUS.
The class ApplicantPositionHistory has 2 references to status one called newStatus and oldStatus.

public class ApplicationPositionHistory
{


  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ApplicationPositionHistoryID { get; set; }

[ForeignKey("ApplicantPositionID")]
public ApplicantPosition ApplicantPosition { get; set; }

[Column("ApplicantPositionID")]
public int ApplicantPositionID { get; set; }

[Column("OldStatusID")]
public int OldStatusID { get; set; }

[Column("NewStatusID")]
public int NewStatusID { get; set; }

[ForeignKey("OldStatusID")]
public Status OldStatus { get; set; }

[ForeignKey("NewStatusID")]
public Status NewStatus { get; set; }

[StringLength(500, MinimumLength = 3, ErrorMessage = "Comments  should not be longer than 500 characters.")]
[Display(Name = "Comments")]
public string Comments { get; set; }

[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Display(Name = "Date")]
public DateTime DateModified { get; set; }
}

In my front end, I have one screen that shows the applicants that have applied to a position

name   position            actions
andew   .net developer     view history

When they click on history they see:
old status     new status      comments         datemodified
new            applied         new prospect
applied        approved by hr  approved by hr

The problem in in the screen where they create Entities of ApplicantPositionHistory.
I want to use the newStatus from the last row as the oldstatus, and the newstatus should be the one that the user selects. (Here is the key of the entire question)

In the code below, newStatus and OldStatus are always pointing to the same ID. So the Insertion works, but its always using the same ID and not showing a real tracking of the statuses history of an applicant.

This is the HTML

<table>    
    <tr>
        <th>
            Previous Status
        </th>
    </tr>
    <tr>
        <td>
             @Html.Label(ViewData["oldStatus"].ToString())
        </td>
    </tr>
</table>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ApplicationPositionHistory</legend>       
        <div class="editor-label">
            New Status
        </div>
        <div class="editor-field">
            @Html.DropDownList("NewStatusID", (IEnumerable<SelectListItem>)ViewBag.Statuses)
            @Html.ValidationMessageFor(model => model.NewStatusID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Comments)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Comments)
            @Html.ValidationMessageFor(model => model.Comments)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

This is the controller action

[HttpPost]
        public ActionResult Create(ApplicationPositionHistory applicationpositionhistory)
        {
            applicationpositionhistory.DateModified = DateTime.Now;

            if (ModelState.IsValid)
            {
                applicationpositionhistory.OldStatusID = applicationpositionhistory.NewStatusID;
                applicationpositionhistory.OldStatus =
                    _unitOfWork.StatusRepository.GetStatusById(applicationpositionhistory.NewStatusID);

                _unitOfWork.ApplicantPositionHistoryRepository.InsertApplicationPositionHistory(applicationpositionhistory);
                _unitOfWork.Save();
                return RedirectToAction("History", new { applicantPositionID = ViewData["applicantPositionId"] });  
            }

            ViewBag.oldStatusID = new SelectList(_unitOfWork.StatusRepository.GetAllStatus(), "StatusID", "status", applicationpositionhistory.OldStatusID);
            ViewBag.newStatusID = new SelectList(_unitOfWork.StatusRepository.GetAllStatus(), "StatusID", "status", applicationpositionhistory.NewStatusID);
            return View(applicationpositionhistory);
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深居我梦 2024-12-20 02:33:37

如果我理解你的问题...两个选项可能是:

1-) 在表单中创建一个值为 OldStatus 的隐藏字段。您可以在 HttpGet 操作的 model/viewModel 中设置它。因此,当表单被发布时,OldStatus 将被绑定。

2-) 在控制器中的创建 [HttpPost] 操作中,而不是:

applicationpositionhistory.OldStatusID = applicationpositionhistory.NewStatusID;

在数据存储/服务中查找最新状态并设置它。我认为这会更好,因为您不必担心高级用户可以修改您的隐藏字段。

顺便说一句,我会考虑创建一个封装此逻辑的域类,而不是让控制器需要担心它。

哈...

If I understood your question...two options could be:

1-) Create a hidden field in the form that has the value of OldStatus. You would set this in the model/viewModel in HttpGet action. Thus when the form is posted, the OldStatus will be bound.

2-) In the controller in the Create [HttpPost] action, instead of:

applicationpositionhistory.OldStatusID = applicationpositionhistory.NewStatusID;

Lookup in your datastore/service what the most recent Status is and set it. I think this would be preferable as you won't have to worry about advanced users that can modify your hidden field.

On a side note, I would consider creating a domain class that encapsulates this logic rather than having controller need to worry about it.

HTH...

玩套路吗 2024-12-20 02:33:37

ViewData 仅在该请求期间存在。它不跨越请求。

处理此问题的一种方法是使用 HiddenFor() 帮助器。这将允许您使用 OldStatusID 创建一个隐藏字段,您可以在下一篇文章中阅读该字段。

ViewData only exists during that request. It does not span requests.

One way of handling this would be using the HiddenFor() helper. This will allow you to create a hidden field with the OldStatusID which you can read on you next post.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文