1

私はMVCが初めてです。ビューのボタンがクリックされたときに、ボタン/div/テキストボックスのテキストを変更できるようにしたいです。オンラインで次のようなチュートリアルを見つけましたが、ボタンをクリックすると別のページにリダイレクトされます。そのページには代わりにテキストが表示されます。デフォルトの Global.aspx には触れていません

意見

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

コントローラ

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

1 に答える 1

1

スクリプトがページに含まれていることを確認jquery.unobtrusive-ajax.jsしてください。

デフォルトのバンドルを使用している場合(見て~/App_Start/BundleConfig.csください-すべてとファイルjqueryvalを組み合わせて最小化する定義済みのバンドルが表示されます):~/Scripts/jquery.unobtrusive*"~/Scripts/jquery.validate*"

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

バンドルを使用しない場合は、このスクリプトのみを個別に含めることができます。

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

Ajax.*ヘルパーが機能するために必要なのはこのスクリプトです。その名前が示すように、目立たないようにそれらをAJAX化します。jQueryに依存するため、jQueryも含まれていることを確認してください。

補足:ASP.NETコントローラーでは、アクションは文字列ではなくActionResultsを返す必要があります。

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

フルビューコードは次のようになります。

@{
    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>

およびコントローラー:

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);
    }
}
于 2012-08-15T16:00:54.860 に答える