Golda
Golda

Reputation: 3891

MVC Ajax not working. Instead of same page, action open in new page

I am working with MVC 5. Ajax coding was not working for me. The following is my coding. Any thing I want to add

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Welcome</title>
</head>
<body>
    <div>
        @using (Ajax.BeginForm("UpdateForm", new AjaxOptions { UpdateTargetId = "textEntered" }))
        {
            @Html.TextBox("textBox1", "Enter text");
            <input type="submit" value="Submit" /><br />
            <span id="textEntered">Nothing Entered</span>                              
        }
})
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")

</body>
</html>

Action

    public string UpdateForm(string textBox1)
    {
        if (textBox1 != "Enter text")
        {
            return "You entered: \"" + textBox1.ToString() + "\" at " +
                DateTime.Now.ToLongTimeString();
        }

        return String.Empty;
    }

When I click the submit button. Its redirect to new page. But in the same page I want to display the value.

Upvotes: 1

Views: 277

Answers (2)

Andrei V
Andrei V

Reputation: 7508

You're not setting the id of the Html.TextBox. The first parameter of the TextBox helper sets the value of the name attribute and not that of the id. Therefore you need to specifically tell the helper which Html attributes to set for your TextBox:

@Html.TextBox("textBox1", 
              "Enter text", 
              new Dictionary<string, object>(){ {"id", "textBox1"} });

Upvotes: 0

Nitin Varpe
Nitin Varpe

Reputation: 10694

Check if property UnobtrusiveJavaScriptEnabled is set to false in my web.config file. If yes change it to true.

Else check

jquery.unobtrusive-ajax.min.js is imported on your page

FOR MORE

Upvotes: 1

Related Questions