简体   繁体   English

将模型的一部分传递给Asp.Net MVC中的View问题

[英]Pass part of model to View problem in Asp.Net MVC

I really didn't know what title to give this question, but I'll explain here: 我真的不知道该问题的标题,但是我将在这里解释:

I have a View with a bunch of input fields in a table. 我有一个视图,在表中有一堆输入字段。 Each row in the table represents a task, and each column a weekday, and the input fields in each cell are there to let the user input hours worked for that task and day. 表中的每一行代表一个任务,每一列代表一个工作日,每个单元格中的输入字段都在其中,以使用户输入该任务和一天的工作时间。

I then have a submit button to post the hours when the user wants to save. 然后,我有一个提交按钮来发布用户想要保存的时间。 But here's the problem: Each timesegment (as the object that holds hours is called) also has the property Description, to let the user write a description of what has been done for a particular time segment reported. 但这是问题所在:每个时间段(称为保存小时的对象)也具有属性Description,以使用户可以为所报告的特定时间段编写已完成操作的描述。

So how could I get the description property for the selected timesegment input field and show it in another "description" input field, and then let the user modify the description and save it with the timesegment? 那么,如何获得所选时间段输入字段的描述属性,并在另一个“描述”输入字段中显示它,然后让用户修改描述并将其与时间段一起保存?

Here's what I've done so far: 到目前为止,这是我所做的:

Action method to get the description: 获取描述的动作方法:

    public ActionResult GetDescription(string name, int number, int year)
    {
        try
        {
            int taskId = Int32.Parse(name.SubstringAfter("Tasks[").Substring(0, 1));
            int timeSegmentId = Int32.Parse(name.SubstringAfter("CurrentTimeSegments[").Substring(0, 1));
            List<Task> tasks = _repository.GetCurrentTasks(number, year);
            var description = tasks[taskId].CurrentTimeSegments[timeSegmentId].Description;

            return Content(description);
        }
        catch (Exception)
        {

            return Content("");
        }
    }

jQuery: jQuery的:

    function getDescription() {
        $('.hourInput').focus(function () {
            var name = $(this).attr('name');
            var number = '<%: Model.WeekNumber %>';
            var year = '<%: Model.Year %>';
            var url = '<%=Url.Action("GetDescription", "Timesheet") %>';
            $.get(url, { name: name, number: number, year: year }, function (data) {
                $('#description').val(data);
            });
        });
    }

Now, as you can see, I have to parse the name attribute of the input field to get the object I'm after, and this seems like a bit of a hack... But it's the only way I can see to get this information. 现在,正如您所看到的,我必须解析输入字段的name属性以获取我所追求的对象,这似乎有点骇人听闻……但这是我看到的唯一途径信息。 So my question is, is there another cleaner way to do this? 所以我的问题是,还有其他更清洁的方法吗?

UPDATE: 更新:

Here's the part that creates the input fields in a nested for loop (looping through each task, and then for each task all its timesegments): 这是在嵌套的for循环(循环遍历每个任务,然后遍历每个任务的所有时间段)中创建输入字段的部分:

<% for (int i = 0; i < Model.Tasks.Count; i++)
           {
               var task = Model.Tasks[i];
        %>
        <tr class="taskrow">
            <td>
                <input type="button" value="Delete" id="<%:i %>" class="deletebutton" />
            </td>
            <td class="customer">
                <%: task.Project.Customer.Name %>
            </td>
            <td class="project">
                <%: task.Project.Name %>
            </td>
            <td class="task">
                <%: task.Name %>
            </td>
            <% for (int j = 0; j < task.CurrentTimeSegments.Count; j++)
               { %>
            <td>
                <%: Html.TextBoxFor(model => model.Tasks[i].CurrentTimeSegments[j].TimeSpanHours, new { @class = "hourInput" })%>
                <%: Html.ValidationMessageFor(model => model.Tasks[i].CurrentTimeSegments[j].TimeSpanHours)%>
            </td>
            <% } %>
            <td class="hourSum"><%:task.WeekTaskHours %></td>
        </tr>
        <% } %>

Note that this code is in a partialview if it matters. 请注意,如果需要的话,此代码位于局部视图中。

you could use the $.data jQuery function to save extra information in your this element of the getDescription method. 您可以使用$.data jQuery函数将额外的信息保存在getDescription方法的this元素中。 You need to do that when you create this element. 创建此元素时,需要这样做。 I don't know how you do that and if it is possible for you in your current design. 我不知道您怎么做,以及您目前的设计是否可行。

to save the information it would be: 保存信息将是:

$(element).data('taskId', taskId);
$(element).data('timeSegmentId', timeSegmentId);

If you give the code where you create this element, I could help you. 如果您在创建此元素的位置提供代码,则可以为您提供帮助。

Then the getDescription method would be 然后, getDescription方法将是

$('.hourInput').focus(function () {
   var taskId = $(this).data('taskId');
   vat timeSegmentId = $(this).data('timeSegmentId');
   var number = '<%: Model.WeekNumber %>';
   var year = '<%: Model.Year %>';
   var url = '<%=Url.Action("GetDescription", "Timesheet") %>';
   $.get(url, { taskId : taskId, timeSegmentId: timeSegmentId, number: number, year: year }, function (data) {
      $('#description').val(data);
   });
});

and so in your controller 所以在你的控制器中

public ActionResult GetDescription(string taskId, string timeSegmentId, int number, int year)
{
   try
   {
      List<Task> tasks = _repository.GetCurrentTasks(number, year);
      var description = tasks[taskId].CurrentTimeSegments[timeSegmentId].Description;

      return Content(description);
   }
   catch (Exception)
   {
      return Content("");
   }
}

EDIT: 编辑:

According to how you create the input text boxes, I think you can do: 根据您如何创建输入文本框,我认为您可以这样做:

<td>
   <%: Html.TextBoxFor(model => model.Tasks[i].CurrentTimeSegments[j].TimeSpanHours, new { @class = "hourInput", id = "uniqueId_" + i + j })%>
   <%: Html.ValidationMessageFor(model => model.Tasks[i].CurrentTimeSegments[j].TimeSpanHours)%>
   <script type="text/javascript">
      $(document).ready(function() {
         var selector = '#uniqueId_<%=i %><%=j %>';
         $(selector).data('taskId', <%=i %>);
         $(selector).data('timeSegmentId', <%=j %>);
      });
   </script>
</td>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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