AlexGH AlexGH - 10 months ago 72
jQuery Question

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

I'm working on a

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
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
attribute from my razor view inside a
element putting in there the url using
. The thing is that when I use
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();
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):

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

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

function ShowSearchPage()

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


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





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

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