分别使用razor和Ajax中的@ Url.Action()调用部分视图

时间:2016-08-02 16:49:06

标签: jquery ajax asp.net-mvc razor

我正在进行SearchStudent()操作,我的代码应该有问题,我错过了一些内容,我还有一个返回{{1的操作方法我希望首先使用Partial View表单显示Partial View Page内的Index page,并在填写表单后使用Search提交表单。我想用ajax做所有这些,所以我希望所有这些都发生在Post request内。 我知道从ajax硬编码我们的网址是一种不好的做法,所以我在Index view元素中使用我的剃刀视图中的data-属性,使用{{1}放入网址}。问题是,当我使用<p>时,它会路由到Index操作而不是@Url.Action()并显示相同的@Url.Action两次,而不是SearchStudent() Action,当我在ajax中进行硬编码时然后它会识别它,发生了什么?

也许您会更好地了解我的代码:

动作方法(我想首先显示局部视图)

Index page

索引视图(仅显示部分视图的部分):

partial view

JQuery函数(如果我直接放在ajax public PartialViewResult SearchStudent() { return PartialView(); } [HttpPost] [ValidateAntiForgeryToken] public JsonResult SearchStudent(string name) { List<Student> list = db.Students.Where(s => s.Name == name).ToList(); return Json(list, JsonRequestBehavior.AllowGet); } 中它可以工作,但这不是一个好习惯):

<div>
    <p class="hand" id="pSearch" data-urlSearch="@Url.Action("SearchStudent","Students")"> Search by name</p>
    <div id="ShowFormSearch"></div>
</div>

2 个答案:

答案 0 :(得分:2)

您的问题是$("#pSearch").data('urlSearch')没有返回Students/SearchStudent。原因是,对于HTML 5数据属性,它应该是小写

替换

$("#pSearch").data('urlSearch')

$("#pSearch").data('urlsearch')

另外,我建议始终使用小写字母设置数据attrbute。

data-urlsearch="@Url.Action("SearchStudent", "Home")"

答案 1 :(得分:1)

您可以尝试更改这样的javascript函数,让我们知道结果是什么:

function ShowSearchPage() {

    var url = $("#pSearch").data('urlSearch');
    alert(url);

    $.ajax({
        type: 'get',
        url: url,
    }).success(function (result) {
        $("#ShowFormSearch").html(result)
    }).error(function () {
        $("#ShowFormSearch").html("An error occurred")
    })
}
相关问题