【问题标题】:Get updated data from partial view editorfor and pass to controller从部分视图编辑器获取更新的数据并传递给控制器
【发布时间】:2019-11-11 20:08:21
【问题描述】:

我已经为此工作了好几个小时。我的部分视图如下所示

_Partial.cshtml

@model project.Jobs
@using (Html.BeginCollectionItem("Jobs"))
{
<tr id="jobrow">
<td>
    @Html.HiddenFor(modelItem => modelItem.JobId)
    @Html.EditorFor(modelItem => modelItem.Description, new { htmlAttributes = new { @class = "" } })
</td>
<td>
    @Html.EditorFor(modelItem => modelItem.FlatRate, new { htmlAttributes = new { @class = "", type = "number", min = "0.00" } })
</td>
<td>
    @Html.EditorFor(modelItem => modelItem.StandardHour, new { htmlAttributes = new { @class = "", type = "number", min = "0.00" } })
</td>
<td>
    @Ajax.ActionLink("Click Me", "AddRepairOrderJobs", "RepairOrderWizard", Model, new AjaxOptions { InsertionMode = InsertionMode.InsertAfter, UpdateTargetId = "rodetailrowdata", HttpMethod = "POST" })

</td>
</tr>
}

这是我渲染局部视图的地方

主视图.cshtml

 @model project.MainViewModel
 @using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <table id="mygrid" class="table">
   <thead>
       <tr>
           <th>Description</th>
           <th>Flat Rate</th>
           <th>Standart Time</th>
           <th>Charge To</th>
           <th></th>
       </tr>
   </thead>
   <tbody id="rodetailrowdata">
       @foreach (var item in Model.MainViewModel.Jobs)
       {
            @Html.Partial("_Partial", item)
       }
   </tbody>
   </table>

使用下面的操作方法,我可以使用上面的 ajax.actionlink 将来自 editorfor 标签的现有数据从部分视图传递到控制器

Controller.cs

[HttpPost]
    public PartialViewResult AddRepairOrderJobs(Jobs job)
    {
        var x = new OtherModel(){
            JobId = job.JobId,
            Name = job.Description,
            SelectedRate = job.FlatRate
            StandardHour = job.StandardHour
        }
        return PartialView("_HeaderDetailList", x);
    }

现在,我想要做的是,当我修改 editorfor 的值时,当我单击操作链接时,我会从 _Partial.cshtml 获取更新的数据,而不是旧的数据,但我可以'让这个工作。 我怎么能在不做一些“黑客工作”的情况下做到这一点?

编辑:我添加了加载作业列表的操作方法

public ActionResult NewRecord()
    {
        var add= new MainViewModel()
        {
            //other data,
            Jobs = jobrepository.GetAllJobs()
        };
        return View(add);
    }

【问题讨论】:

  • 你试过用@for代替@foreach吗?
  • @Rafalon 这会有什么不同?我是 mvc 新手。
  • 我不确定部分视图,但索引。在一个循环中,拥有 @Html.EditorFor(m =&gt; m.Items[i].PropA) 允许它在 @Html.EditorFor(m =&gt; item.PropA) 不返回时返回(您可能需要检查生成的 html 以了解原因)
  • 我试试看,一会儿回来
  • 因为您使用了 Ajax.ActionLink,它使用旧模型数据生成了一个固定的 URL。因此,无论何时更改数据,它都不会更新。您可以检查“点击我”以查看更多详细信息。

标签: c# ajax model-view-controller


【解决方案1】:

我使用@Tomato32 的提示解决了我的问题。我只需要将 Jobs 模型放在主视图而不是部分视图中循环,然后将我的 viewmodel 作为参数而不是作业模型传递。现在我得到了一切,包括更新的工作数据。如果有人需要,我可以包含代码。

【讨论】:

  • 很好的解决方案。你太棒了,我的朋友:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多