@jtml.BeginForm使用jquery Ajax并不能完全工作

时间:2017-05-15 21:11:05

标签: jquery asp.net ajax

我必须在一个公式上使用Ajax和asp.net mvc。我的经理不希望我使用@ Ajax.BeginForm,所以我必须使用ajax和Jquery方法。 我的问题是,即使我的代码似乎工作,当它进入控制器,控制器返回一个新页面(就像表单是通过简单的POST提交),所以我没有ajax的优势。我真的不知道我在哪里犯了错误,或者我是不是错了。这是我的代码:

HTML:

@using (Html.BeginForm("AddCtrl", null, FormMethod.Post,new { id = "addGroupForm" }) )
{
    @Html.AntiForgeryToken()
    <div class="row">
        <div class="row">
            <div class="input-field col s6">
                <i class="material-icons prefix">perm_identitye</i>
                @Html.LabelFor(model => Model.group.Name, htmlAttributes: new { id = "Description" })
                @Html.EditorFor(model => model.group.Name, new { htmlAttributes = new { @class = "validate" } })
                @Html.ValidationMessageFor(model => model.group.Name, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
    <div class="input-field col s12">
    </div>

    @Html.ListBoxFor(model => model.idList, new MultiSelectList(Model.permissionList, "Id" , "Name"), null)


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-primary" />
        </div>
    </div>

}

JS:

$(function () {
        $('#addGroupForm').submit(function () {
            alert(this.methode);
            if ($(this).valid()) {
                //the action is send with this ajax request and the send works
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        alert("yo");
                    }
                });
            }
            return false;
        });
    });

控制器:

[HttpPost]
        public ActionResult AddCtrl(GroupViewModels grp)
        {
            System.Diagnostics.Debug.WriteLine("YOOOOOOOOOOOOOOOOOOOOO");
            System.Diagnostics.Debug.WriteLine(grp.group.Name);
            return Json("{yo:toto}");
        }

1 个答案:

答案 0 :(得分:1)

在表单提交时使用ajax时,您需要使用using System.Collections; using System.Collections.Generic; using UnityEngine; public class Teleport : MonoBehaviour { public Vector3 terrainArea; public float spinSpeed = 2.0f; public int cloneTeleportations; public GameObject prefab; private bool rotate = false; private bool exited = false; private Transform[] teleportations; private Random rnd = new Random(); private void Start() { GameObject go = GameObject.Find("Terrain"); Terrain terrain = go.GetComponent(Terrain); terrainArea = terrain.terrainData.size; for (int i = 0; i < cloneTeleportations; i++) { GameObject Teleportaion = Instantiate(prefab, new Vector3(Random.Range(i * 10.0F, i * 50.0F), 0, Random.Range(i * 10.0F, i * 50.0F)), Quaternion.identity); Teleportaion.transform.parent = this.transform; Teleportaion.transform.tag = "Teleportation"; } } } 而不是e.preventDefault()

试试这个:

return false