user1134179
user1134179

Reputation: 539

MVC 4 Updating a view with a controller action

I'm new to MVC. I want to be able to change a button/divs/textboxes text when a view's button is clicked. I found a tutorial online that showed me the following but when I click the button I'm getting redirected to another page. That page shows the text instead. I haven't touched the default Global.aspx

View

@using (Ajax.BeginForm("ExamineTextBox", new AjaxOptions { UpdateTargetId = "result" }))
{
    @Html.TextBox("textBox1")
    <input type="submit" value="Button" />
    <span id="result" />
}

Controller

public string ExamineTextBox(string textBox1)
{
    if (textBox1 != "Initial Data")
    {
        return "This text is MVC different from before!";
    }
    return String.Empty;
}

Upvotes: 1

Views: 9099

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

Make sure you have included the jquery.unobtrusive-ajax.js script to your page.

If you are using the default bundles (take a look at ~/App_Start/BundleConfig.cs - you will see a jqueryval bundle defined which combines and minifies all ~/Scripts/jquery.unobtrusive* and "~/Scripts/jquery.validate*" files):

@Scripts.Render("~/bundles/jqueryval")

and if not using bundles you could include only this script individually:

<script type="text/javascript" src="~/scripts/jquery.unobtrusive-ajax.js"></script>

It is this script that is required for Ajax.* helpers to work. As it name indicates it unobtrusively AJAXifies them. It depends on jQuery so make sure you have that one included as well.

Side note: In ASP.NET controller actions should return ActionResults, not strings:

public ActionResult ExamineTextBox(string textBox1)
{
    if (textBox1 != "Initial Data")
    {
        return Content("This text is MVC different from before!");
    }
    return Content(String.Empty);
}

Here's how your full view code might look:

@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
    </head>
    <body>
        @using (Ajax.BeginForm("ExamineTextBox", new AjaxOptions { UpdateTargetId = "result" }))
        {
            @Html.TextBox("textBox1", "Initial Data")
            <input type="submit" value="Button" />
            <span id="result" />
        }
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/jqueryval")
    </body>
</html>

and the controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult ExamineTextBox(string textBox1)
    {
        if (textBox1 != "Initial Data")
        {
            return Content("This text is MVC different from before!");
        }
        return Content(String.Empty);
    }
}

Upvotes: 1

Related Questions