你能更新局部视图而不是整页帖子吗?

时间:2013-02-28 21:43:53

标签: asp.net-mvc jquery knockout.js partial-views

有没有办法在asp.net mvc中提交部分视图表单而不重新加载父页面,但是只将部分视图重新加载到新状态?与knockout.js如何使用data-bind更新类似。

我的数据表使用可变数量的列/名称进行渲染,因此我认为knockout.js不是这个选项的一个选项,所以我尝试使用局部视图。

5 个答案:

答案 0 :(得分:45)

不是没有jQuery。

你需要做的就是把你的Partial放在div中,比如:

<div id="partial">
    @Html.Partial("YourPartial")
</div>

然后,要更新(例如点击标识为button的按钮),您可以执行以下操作:

$("#button").click(function () {
   $.ajax({
       url: "YourController/GetData",
       type: "get",
       data: $("form").serialize(), //if you need to post Model data, use this
       success: function (result) {
           $("#partial").html(result);
       }
   });
})

然后你的行动看起来像:

public ActionResult GetData(YourModel model) //that's if you need the model
{
    //do whatever

    return View(model);
}

答案 1 :(得分:13)

实际上,如果你的Partial有一个子动作方法,你可以直接发布(甚至使用锚链接)到子动作,并获得类似Ajax的效果。我们在几个视图中执行此操作。

语法是

@Html.Action("MyPartial")

儿童行动是

public ActionResult MyPartial()
{
    return PartialView(Model);
}

如果您的表单发布到子操作

@using (Html.BeginForm("MyPartial"))
{
    ...
}

将使用子操作返回的部分视图更新部分视图。

Jquery仍然是更新部分的合法方式。但从技术上讲,你的问题的答案是肯定的。

答案 2 :(得分:2)

我会使用Ajax Form帮助程序使用部分视图和@ html.RenderPartial(“partialName”)这样的场景 partial helpers

答案 3 :(得分:2)

正常情况下,我在寻找这样的事情时发现人们提供的信息太有限,所以我会尝试在这里提供帮助。关键是要设置一个带有ID的div,你可以将返回html附加到。在击中控制器时也要确保它返回部分控制器。这种方法存在一些潜在的问题,但在美好的一天它应该有效。

<div id="CategoryList" class="widget">
    @{
        Html.RenderPartial("WidgetCategories.cshtml");
    }
</div>

          function DeleteCategory(CategoryID) {
            $.get('/Dashboard/DeleteWidgetCategory?CategoryID=' + CategoryID,
                function (data) {
                    if (data == "No") {
                        alert('The Category has report widgets assigned to it and cannot be deleted.');
                    }
                    else {
                        $('#CategoryList').html(data);
                    }

                }
            );
        }


    [HttpGet("DeleteWidgetCategory")]
    [HttpPost("DeleteWidgetCategory")]
    public IActionResult DeleteWidgetCategory(string CategoryID)
    {
        string Deleted = CategoryModel.DeleteCategory(CategoryID);

        if (Deleted == "Yes")
        {
            return PartialView("WidgetCategories");
        }
        else
        {
            return this.Json("No");
        }
    }

答案 4 :(得分:0)

在主视图中

<div id=SearchResult>
   @Html.Partial("_NameOfPartialView", Model)
</div>

<input type="button" id="btnSubmit" value="Submit">

在您的Javascript文件中

$('#btnSubmit').click(function () {
    GetData(Id);
});

function GetData(Id){
  $.ajax({
     url: "/Home/GetEmployee/",
     type: "get",
     data: { Id:Id },
     success: function (result) {
     $('#SearchResult').html(result);
     }
   });
}

在家庭控制器中

public ActionResult GetEmployee(int Id)
{
   var employee= context.Employee.Where(x=> x.EmployeeId == Id)

   return this.PartialView("_NameOfPartialView", employee);
}
相关问题