Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DropdownListFor在更改时更新并发布父对象_C#_Jquery_Asp.net_Asp.net Mvc 4_Razor - Fatal编程技术网

C# DropdownListFor在更改时更新并发布父对象

C# DropdownListFor在更改时更新并发布父对象,c#,jquery,asp.net,asp.net-mvc-4,razor,C#,Jquery,Asp.net,Asp.net Mvc 4,Razor,我觉得我的项目会很好也很简单 我的问题是: 我正在使用MVC4为项目经理制作一个清单,我为每个任务项都有一个编辑器模板。在每个任务项中,我都有一个DropDownList,用户可以使用它来选择任务状态(“完成”、“正在进行”等) 当用户更改任务状态时,脚本将继续并添加完成日期(如果更改为完成状态)。我还希望它使用我的HttpPost方法“UpdateTaskState”更新并保存数据库中的任务更改 作为一个附带问题,这是实现我的目标的正确和恰当的方法吗?我很想拥有它,这样我就不需要每次进行更改时

我觉得我的项目会很好也很简单

我的问题是:

我正在使用MVC4为项目经理制作一个清单,我为每个任务项都有一个编辑器模板。在每个任务项中,我都有一个DropDownList,用户可以使用它来选择任务状态(“完成”、“正在进行”等)

当用户更改任务状态时,脚本将继续并添加完成日期(如果更改为完成状态)。我还希望它使用我的HttpPost方法“UpdateTaskState”更新并保存数据库中的任务更改

作为一个附带问题,这是实现我的目标的正确和恰当的方法吗?我很想拥有它,这样我就不需要每次进行更改时都刷新tasks视图

我的任务编辑器模板:

@model Models.task

@Html.HiddenFor(model => model.task_id, new { @id = "taskID" })
@Html.HiddenFor(model => model.task_name)
@Html.HiddenFor(model => model.task_desc)
@Html.HiddenFor(model => model.user_completed,new {@id = "UserCompleted" })
@Html.HiddenFor(model => model.completion_date, new { @id = "CompletionDate" })

<table style="width:80%">
    <tr style="width:60%">
        <th colspan="3">@Html.DisplayFor(model => model.task_name)</th>
        <th align="left">
        @Html.DropDownListFor(model => model.task_state_id,
    new SelectList((System.Collections.IEnumerable)ViewData["TaskStates"], "task_state_id", "state"),
             new { @Id = "ddlState" })
    </th>
        <td>
            @Html.EditorFor(model => model.notes, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.notes, "", new { @class = "text-danger" })
        </td>    
    </tr>
    <tr>
        <td colspan="3">@Html.DisplayFor(model => model.task_desc)</td>
        <td>@Html.Label("Completed by ")@Html.DisplayFor(model => model.user_completed)@Html.Label(", ")@Html.DisplayFor(model => model.completion_date)</td>
    </tr>
</table>
@model Models.task
@Html.HiddenFor(model=>model.task_id,new{@id=“taskID”})
@Html.HiddenFor(model=>model.task_name)
@Html.HiddenFor(model=>model.task_desc)
@Html.HiddenFor(model=>model.user_completed,new{@id=“UserCompleted”})
@Html.HiddenFor(model=>model.completion_date,new{@id=“CompletionDate”})
@DisplayFor(model=>model.task_name)
@Html.DropDownListFor(model=>model.task\u state\u id,
新建SelectList((System.Collections.IEnumerable)视图数据[“任务状态”],“任务状态id”,“状态”),
新的{@Id=“ddlState”})
@EditorFor(model=>model.notes,new{htmlAttributes=new{@class=“form control”})
@Html.ValidationMessageFor(model=>model.notes,“,new{@class=“text danger”})
@DisplayFor(model=>model.task_desc)
@Html.Label(“完成人”)@Html.DisplayFor(model=>model.user\u Completed)@Html.Label(“,”@Html.DisplayFor(model=>model.completion\u date)
我的脚本主视图:

@model NSCEngineering.Models.NRIAndCategoriesViewModel
@{ ViewBag.Title = "Details";}

<h2>Details</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
    <div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Save" class="btn btn-default" />
    </div>
</div>

<div class="form-horizontal">
    <hr />
    @Html.HiddenFor(item => Model.TaskStates)
    @Html.HiddenFor(item => Model.id, new{ @id ="NriID" })
    <div class="NRISummary">
    @Html.LabelFor(item => Model.Summary )
    @Html.DisplayFor(item => Model.Summary, "_nri")
        </div>
    <hr />
    <div class="tasks">  
    @Html.LabelFor(item => Model.Tasks )
        @for (int i = 0; i < Model.Tasks.Count(); i++ )
        {
            @Html.EditorFor(item => Model.Tasks[i], "_task", new{@id = "taskItem"})
        }
        </div>
    </div>
}

<p>
    @Html.ActionLink("Back to List", "Index")
</p>

@section Scripts{

<script type="text/javascript">
    $(this.document).ready(function () {
    $('#ddlState').change(function () //wire up on change event of the 'country' dropdownlist
    {
        var selection = $('#ddlState').val(); //get the selection made in the dropdownlist
        if (selection == '4') {
            $('#CompletionDate').val('@DateTime.Now.Date');
        }
        var completion = $('#CompletionDate').val();
        alert(completion);
        alert($('#taskID').val());
        var url = '@Url.Action("UpdateTaskState", "nris")';
        $.ajax({
            url: url,
            type: 'POST',
            data: $('#taskItem').serializeArray(),
            contentType: "application/json; charset=utf-8",
            success: function (e) {
                $("#message").html("Success");
            },
            error: function (xhr, status, error) {
                // Show the error
                $('#message').html(xhr.responseText);
            }
        })

    })
});
@model.engineering.Models.NRIAndCategoriesViewModel
@{ViewBag.Title=“详细信息”;}
细节
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()

@Html.HiddenFor(item=>Model.TaskStates) @HiddenFor(item=>Model.id,新的{@id=“NriID”}) @LabelFor(item=>Model.Summary) @DisplayFor(item=>Model.Summary,“\u nri”)
@LabelFor(item=>Model.Tasks) @对于(int i=0;iModel.Tasks[i],“_task”,new{@id=“taskItem”}) } } @ActionLink(“返回列表”、“索引”)

@节脚本{ $(this.document).ready(函数(){ $('#ddlState').change(函数()//连接'country'下拉列表的更改事件 { var selection=$('#ddlState').val();//获取在dropdownlist中进行的选择 如果(选择=='4'){ $('#CompletionDate').val('@DateTime.Now.Date'); } var completion=$(“#CompletionDate”).val(); 警报(完成); 警报($('#taskID').val()); var url='@url.Action(“UpdateTaskState”、“nris”); $.ajax({ url:url, 键入:“POST”, 数据:$('#taskItem').serializeArray(), contentType:“应用程序/json;字符集=utf-8”, 成功:职能(e){ $(“#消息”).html(“成功”); }, 错误:函数(xhr、状态、错误){ //显示错误 $('#message').html(xhr.responseText); } }) }) });
}

更新1

@model NSCEngineering.Models.NRIAndCategoriesViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
            <p>
                @Html.ActionLink("Back to List", "Index")
            </p>
        </div>
    </div>
    @Html.LabelFor(item => Model.nriSummary)
    @Html.DisplayFor(item => Model.nriSummary, "_nri")  //just displays project summary details
    <div class="form-group">        
        @for (int i = 0; i < Model.Categories.Count; i++)
        {
            <div style="border:solid ; border-width:1px">
               <table class="category" style="width:100%">
                   <thead style="font-size:large ; background-color:black">
                      @Html.DisplayFor(c => c.Categories[i].category_name)
                   </thead>
                   <tbody>
                       <tr>
                           @renderTasksControl(Model.Categories[i].tasks, Model.StateList)
                       </tr>                           
                       @for (int k = 0; k < Model.Categories[i].Subcategories.Count; k++)
                       {
                           <tr>
                               <td>
                                   <table>
                                       <thead style="font-size:larger">
                                           @Html.DisplayFor(c => c.Categories[i].Subcategories[k].category_name)
                                           @renderCategoryPercentage(Model.Categories[i].Subcategories[k].tasks)
                                       </thead>
                                       <tbody>
                                           @renderTasksControl(Model.Categories[i].Subcategories[k].tasks, Model.StateList)
                                       </tbody>
                                   </table>
                               </td>
                            </tr>                           
                       }
                   </tbody>
               </table>
                </div>
        }
        </div>
}


@helper renderTasksControl(IList<NSCEngineering.Models.task> TaskList, SelectList states) {
    for (int i = 0; i < TaskList.Count; i++) { 
    <div class="task">
                @Html.DisplayFor(model => TaskList[i].task_name)   
                @Html.DropDownListFor(model => TaskList[i].task_state_id, states, new { @class = "ddlState" })
                @Html.HiddenFor(model => TaskList[i].task_id)
                @Html.HiddenFor(model => TaskList[i].nri_id)
                @Html.DisplayFor(model => TaskList[i].completion_date, new { @class = "date" })
                @Html.HiddenFor(model => TaskList[i].category_id)

                @*@Html.EditorFor(model => Task.notes)
                @Html.ValidationMessageFor(model => Task.notes, "", new { @class = "text-danger" })*@
            @Html.DisplayFor(model => TaskList[i].task_desc)
        @Html.DisplayFor(model => TaskList[i].user_completed)

</div>
}
}

@helper renderCategoryPercentage(IList<NSCEngineering.Models.task> taskList) { 
   int sum = 0;
   int total = 0;
   var percentage = "";
     foreach (NSCEngineering.Models.task task in taskList)
    {
        if (task.task_state_id != -1) { 
             sum += task.task_state_id;
        }
         total += 3;         
    }
     if (total != 0){
         var ratio = ((double)sum / total);
         percentage = string.Format("{0:0.0%}", ratio);
         }
     else { 
         percentage = "Invalid Value";
     }
    <text> @sum + @total </text> 
    <br />
    @percentage
};  

@section Scripts{

<script type="text/javascript">
 //this is me trying to get the completiondate to programatically update
    $(this.document).ready(function () {
        $('.ddlState').change(function () {
            if ($('.ddlState').val() == 3) {
                date = '@DateTime.Now.Date';
                var task = $(this).closest('.task');
                var completionDate = task.children('.date');
                task.children($('.date')).text(date);
                alert(date);
                alert(task.children($('.date')).text());
            }
            else {
                $('.completion_date').val(null);
            }
        //    location.reload(true);
        })
    });
</script>
}

public partial class category
{
    public category()
    {
        tasks = new List<task>();
        Subcategories = new List<category>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public byte category_id { get; set; }

    [Required]
    public string category_name { get; set; }
    public byte? parent_category_id { get; set; }

    [ForeignKey("parent_category_id")]
    public category ParentCategory { get; set; }

    [InverseProperty("ParentCategory")]
    public virtual IList<category> Subcategories { get; set; }

    public virtual IList<task> tasks { get; set; }
}
@model.engineering.Models.NRIAndCategoriesViewModel
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()

@ActionLink(“返回列表”、“索引”)

@LabelFor(item=>Model.nriSummary) @DisplayFor(item=>Model.nriSummary,“\u nri”)//只显示项目摘要详细信息 @对于(int i=0;ic.Categories[i].Categories\u名称) @renderTasksControl(Model.Categories[i].任务,Model.StateList) @对于(int k=0;kc.Categories[i]。子类别[k]。类别名称) @RenderCategory百分比(模型.类别[i].子类别[k].任务) @renderTasksControl(模型。类别[i]。子类别[k]。任务,模型。状态列表) } } } @helper renderTasksControl(IList任务列表,SelectList状态){ 对于(inti=0;iTaskList[i].task\u name) @DropDownListFor(model=>TaskList[i].task_state_id,states,new{@class=“ddlState”}) @Html.HiddenFor(model=>TaskList[i].task\u id) @Html.HiddenFor(model=>TaskList[i].nri\u id) @DisplayFor(model=>TaskList[i]。完成日期,新的{@class=“date”}) @Html.HiddenFor(model=>TaskList[i].category\u id) @*@热媒
public class TaskViewModel
{
  public int ID { get; set; }
  public string Name { get; set; }
  public int State { get; set; }
  public string Description { get; set; }
  public string Notes { get; set; }
}

public class NRIAndCategoriesViewModel
{
  public List<TaskViewModel> Tasks { get; set; }
  public SelectList StateList { get; set; }
  // other properties of the model to display in the main view
}
@model NSCEngineering.Models.NRIAndCategoriesViewModel
@using (Html.BeginForm())
{
  ...
  for (int i = 0; i < Model.Tasks.Count; i++)
  {
    <div class="task">
      @Html.HiddenFor(m => m.Tasks[i].ID, new { @class = "id" })
      @Html.DisplayFor(m => m.Tasks[i].Name)
      @Html.DropDownListFor(m => m.Tasks[i].State, Model.StateList, new { @class = "state" })
      @Html.TextAreaFor(m => m.Tasks[i].Notes, new { @class = "notes" })
      @Html.DisplayFor(m => m.Tasks[i].Description)
    </div>
  }
  <input type="submit" value="Save" />
}
@Html.EditorFor(m => m.Tasks)
public ActionResult UpdateTaskState(NRIAndCategoriesViewModel viewModel)
var url = '@Url.Action("UpdateTaskState", "nris")';
$('.State').change(function() {
  var state = $(this).val();
  var task = $(this).closest('.task');
  var id = task.children('.id').val();     
  var notes = task.children('.notes').val();
  $.post(url, {ID: id, State: state, Notes: notes }, function(response) {
    // do something with the response
  });
});
public ActionResult UpdateTaskState(TaskViewModel viewModel)