Ajax post not working MVC 5

I'm trying to post data into a controller but it doesn't seems to work, I need the post to include the content of the view into a div when done but I cant quite achieve it

Here's my js function:

function show(num) {
    $.ajax({
        dataType: "html",
        type: "POST",
        url: "Student/Schedule",
        data: { number: num },
        success: function (a) {
            // Replace the div's content with the page method's return.
            alert("success");
            $('#schedule').load(a);
        }
    });
}

And, here's my controller:

public ActionResult Schedule(String number)
{
    return View(number);
}

I am a noob in MVC and C#, so any help is welcome.

Upvotes: 1

Views: 15294

Answers (3)

Leandro Soares
Leandro Soares

Reputation: 2972

I had the same issue what i did was adding jquery.unobtrusive-ajax.js to my scripts

Upvotes: 1

Reza Aghaei
Reza Aghaei

Reputation: 125197

There are somethings that you should fix to solve the problem.

  • Change Url to "/Student/Schedule"

    You are using "Student/Schedule" as url, so you are trying to call an action named "Student".

  • Add [HttpPost] to your action.

  • You should return PartialView("Schedule", number);.

    When you use return View(number) it uses the string value of number as your view name. You should explicitly pass view name and model.

  • Use $('#schedule').html(a);

It's better to add an error function to your ajax call to be able to find errors:

error: function (jqXHR, textStatus, errorThrown) { 
    alert(errorThrown); 
    //or you can put jqXHR.responseText somewhere as complete response. Its html.
}

Upvotes: 3

ataravati
ataravati

Reputation: 9155

Your action should return a Partial View, not a View.

Change your action to:

[HttpPost]
// by the way use string instead of String
public ActionResult Schedule(string number) 
{
    return PartialView("_Schedule", number);
}

Then, you'll need to create a partial view named _Schedule.cshtml.

Also, you need to change $('#schedule').load(a); to $('#schedule').html(a); And, I'd suggest that you use a Url.Action to set your url in your ajax call, like this:

function show(num) {
    $.ajax({
        dataType: "html",
        type: "POST",
        url: '@Url.Action("Schedule", "Student")',
        data: { number: num },
        success: function (a) {
            // Replace the div's content with the page method's return.
            alert("success");
            $('#schedule').html(a);
        }
    });
}

Upvotes: 1

Related Questions