Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC 3 - Ajax.BeginForm does a full post back

In the following code, I'm using Ajax.BeginForm to post data to the action asynchronously. The action gets called but the results are displayed to a new web page. I'v looked at a ton of example. This doesn't seem difficult. I've made the example extremely simple for a proof of concept (poc), but I'm still seeing a new page displayed.

Controller

  [HttpPost]
    [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
    public string TestAjax(UserViewModel viewModel)
    {

        return viewModel.UserName;
    }

View

@model BasicMvc3Example2.Models.UserViewModel

@{
    ViewBag.Title = "Index2";
    Layout = null;//"~/Views/Shared/_Layout.cshtml";
}

      <script src="/BasicMvc3Example2/Scripts/jquery-1.4.4.js" type="text/javascript"></script>
    <script src="/BasicMvc3Example2/Scripts/jquery-ui.js" type="text/javascript"></script>
    <script src="/BasicMvc3Example2/Scripts/jquery.validate.js" type="text/javascript"></script>
    <script src="/BasicMvc3Example2/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
    <h2>Index2</h2>

    <script type="text/javascript">
        function PostFailure(){
            alert("Failure");
        }

        function PostSuccess(){
            alert("Success");
        }

        function PostOnComplete() {
            alert("Complete");
        }
    </script>

    Page Rendered: @DateTime.Now.ToLongTimeString()
    @using (Ajax.BeginForm("TestAjax", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "textEntered", OnFailure = "PostFailure", OnSuccess = "PostSuccess", OnComplete = "PostOnComplete" }))
    {
        <div>
           @Html.LabelFor(m => m.UserName)
           @Html.TextBoxFor(m => m.UserName)
        </div>

        <div>
           @Html.LabelFor(m => m.Password)
           @Html.TextBoxFor(m => m.Password)
        </div>

        <div>
           @Html.LabelFor(m => m.EmailAddress)
           @Html.TextBoxFor(m => m.EmailAddress)
        </div>

        <input type="submit" id="submitForm" value="Submit Form" />
    }

    <div id="textEntered">d</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can you check _Layout.cshtml and make sure the ajax script is referenced? I don't think it is by default:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...