AlexGH AlexGH - 4 months ago 26
jQuery Question

Call Partial View using @Url.Action() from razor and Ajax separately

I'm working on a

SearchStudent()
action, there should be something wrong with my code, something that I'm missing, I've an action method that returns a
Partial View
, I want to show first the
Partial View Page
inside the
Index page
with the
Search
form and once filled the form submit it using a
Post request
. I want to do all that using ajax so I want all that to happen inside the
Index view
..
I know that is a bad practice to hardcode our url from ajax, so I'm using the
data-
attribute from my razor view inside a
<p>
element putting in there the url using
@Url.Action()
. The thing is that when I use
@Url.Action
it routes to the Index action instead of the
SearchStudent() Action
and shows the same
Index page
twice instead of the
partial view
and when I hardcode in ajax the url then it recognizes it, what's happening?

Maybe you'll understand better seeing my code:

Action Method(I want to show the partial view first)

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);
}


Index view(just the section concerning to show the Partial View):

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


JQuery function(if I put directly inside ajax
url: "Students/SearchStudent"
it works but that is not a good practice):

function ShowSearchPage()

{
$.ajax({
type: 'get',
url: $("#pSearch").data('urlSearch'),
}).success(function (result) {
$("#ShowFormSearch").html(result)
}).error(function () {
$("#ShowFormSearch").html("An error occurred")
})
}

Answer

Your problem is $("#pSearch").data('urlSearch') is not returning Students/SearchStudent. The reason is, for HTML 5 data attrbutes, it should be lowercase.

Replace

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

with

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

Also i recommend using lowercase always for setting the data attrbute.

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