按钮点击事件无效

3

View

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<fieldset>
    <br />
    <br />
    <br />

     <div align="center">

     @{

        @(Html.Telerik().Grid<SmartTrack.Web.DAL.SysUserList>()
        .DataBinding(dataBinding => dataBinding.Ajax().Select("Index", "User"))
        .Name("UserList")
        .DataKeys(keys => keys
            .Add(c => c.UserName)
            .RouteKey("UserName"))
        .Columns(columns =>
        {
            columns.Bound(o => o.UserName).Width(100);
            columns.Bound(o => o.FirstName).Width(200);
            columns.Bound(o => o.LastName).Width(250);
            columns.Bound(o => o.Active).ClientTemplate("<input type='checkbox' disabled='disabled' name='Active' <#=Active? checked='checked' : '' #> />").Width(70).HtmlAttributes(new { style = "text-align:center" }); ;


        })
        .Pageable(pagerAction => pagerAction.PageSize(20))
        .Sortable()
        .Selectable()
        .Scrollable()
        .Groupable()
        .Filterable()
        .HtmlAttributes(new { style = "width:50%;" })
       )
         }
       </div>
       <br/>
       <div align="center">
        <table>
        <tr>
        <td>
            <button id="btnAdd" type="submit" style="height:40px;width:70px" ">Add</button>
            </td>
            <td>
            <button style="height:40px;width:70px" ">Edit</button>
            </td>
            <td>
            <button style="height:40px;width:70px" ">Delete</button>
            </td>
        </tr>
        </table>   
       </div>
       </fieldset>

<script type="text/javascript">
    $(function () {
        $('#btnAdd').click(function () {
            $.ajax({
            type: "POST",
            url: '@Url.Action("Create","User")',
            success: function (result) {
                $('#cuscreate').html(result)
            }
            });
        });
    });
    </script>

这个视图包含一个脚本,当点击添加按钮时,会调用UserController的Create方法。

控制

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SmartTrack.Web.Attributes;
using SmartTrack.Web.Models;
using SmartTrack.Web.DAL;
using Telerik.Web.Mvc;
namespace SmartTrack.Web.Controllers
{
    public class UserController : Controller
    {
        SMARTTrackerEntities db = new SMARTTrackerEntities();

        //
        // GET: /User/
        [GridAction]
        public ActionResult Index()
        {
            //ViewData["UserGroup"] = DisplayContentEngine.getUserGroupList();

            return View(new GridModel(UserListEngine.getAllSystemUser()));
        }

        [HttpPost] 
        public ActionResult Create()
        {

            ViewData["Location"] = DisplayContentEngine.getLocationList();
            ViewData["Branch"] = DisplayContentEngine.getBranchList();
            //var v = ViewData.Model = UserListEngine.getAllSystemUser();
            var user = new SysUserList();

            return View(user);
        }

        [HttpPost]
        public ActionResult Create(SysUserList user)
        {
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {

                    //Save Registration
                    db.SysUserLists.AddObject(user);
                    db.SaveChanges();

                    return RedirectToAction("Index");
                }
                return View(user);
            }
            catch
            {
                return View();
            }

        }

        public ActionResult Edit(string username)
        {
            SysUserList sysuserlist = db.SysUserLists.Single(s => s.UserName == username);
            return View(sysuserlist);

        }
    }
}

这是一个被称为控制器的组件。

创建视图

@model SmartTrack.Web.DAL.SysUserList

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

<h2>Create</h2>


@using (Html.BeginForm())
{
    <div id="cuscreate">
        <fieldset>

        <table>
            <tr>
                <td>
                    <label>First Name</label>
                </td>
                <td>
                    @Html.TextBoxFor(model => model.FirstName)
                </td>
                <td>
                    <label>Last Name</label>
                </td>
                <td>
                    @Html.TextBoxFor(model => model.LastName)
                </td>
            </tr>
            <tr>
                <td>
                    <label>User Name</label>
                </td>
                <td>
                    @Html.TextBoxFor(model => model.UserName)
                </td>
                <td>
                    <label>Password</label>
                </td>
                <td>
                    @Html.PasswordFor(model => model.userPwd)
                </td>
            </tr>
            <tr></tr>
            <tr>
                <td>
                    <label>Location</label>
                </td>
                <td>
                    @(Html.Telerik().DropDownList()
                    .Name("ddLocation")
                    .BindTo((IEnumerable<DropDownItem>)ViewData["Location"])
                    .CascadeTo("ddlBranch")
                    )
                </td>
                <td>
                     <label>Branch</label>
                </td>
                <td>
                    @(Html.Telerik().DropDownList()
                    .Name("ddlBranch")
                    .BindTo((IEnumerable<DropDownItem>)ViewData["Branch"])
                    )
                </td>
            </tr>

        </table>


        </fieldset>
    </div>
}

当点击添加按钮时,没有任何反应,有人能告诉我问题出在哪里吗?
提前感谢。
敬礼, Kurt

尝试在Chrome或Firefox中运行Firebug - 检查控制台以查看发送的数据和/或错误。 - naspinski
4个回答

2

我看不到你的html中有表单标签,这可能是它不知道要发布在哪里的原因。

带有动作链接“创建新”和Telerik网格的视图中没有表单标签。


2

你的ajax请求中没有数据元素,因此你没有POST任何内容。

如果你想从表单中获取数据,只需要使用.serialize()方法:

$.ajax({
    type: "POST",
    data: $('form').serialize(),
    url: '@Url.Action("Create","User")',
    success: function (result) {
        $('#cuscreate').html(result)
    }
});

请记住,这只有在页面上只有一个 标签时才有效,否则您应该使用另一个选择器,但您已经明白了。

更新来自HatSoft的答案(点赞它!):

通常在您的 标签内部,您应该有 标签,在MVC中执行此操作:

<fieldset>
    @using(Html.BeginForm())
    {
        <p>your form</p>
    }
</fieldset>

我应该放置哪个数据元素? - Allikurt
我已经尝试了所有建议,但仍未获得期望的结果。 - Allikurt
你尝试过运行Firebug来查看你的请求在做什么吗(如果有的话)? - naspinski
我没有收到错误信息,只是页面没有刷新为所调用的页面。 - Allikurt
从 Firebug 中的响应显示它正在调用正确的视图。但正如我之前所说,页面没有刷新以显示 UI。 - Allikurt
你建议使用另一个选择器,我该如何操作?能否给我提供一个例子?先谢谢了。 - Allikurt

2

请确保通过从单击处理程序返回false来取消提交按钮的默认操作,以便给您的AJAX调用执行的机会:

<script type="text/javascript">
    $(function () {
        $('#btnAdd').click(function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("Create", "User")',
                success: function (result) {
                    $('#cuscreate').html(result)
                }
            });
        });

        return false; // <!-- That's the important bit
    });
</script>

我已经尝试了所有建议,但仍未获得期望的结果。 - Allikurt

0
在纠正我的问题时,我不得不修改我的索引视图以包括div id = cuscreate,这导致了CreateUser视图的显示。
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<div id="cuscreate" align="center">
 <fieldset>
    <br />
    <br />
    <br />


      @using (Html.BeginForm())
      {
        //@{

        @(Html.Telerik().Grid<SmartTrack.Web.DAL.SysUserList>()
        .DataBinding(dataBinding => dataBinding.Ajax().Select("Index", "User"))
        .Name("UserList")
        .DataKeys(keys => keys
            .Add(c => c.UserName)
            .RouteKey("UserName"))
        .Columns(columns =>
        {
            columns.Bound(o => o.UserName).Width(100);
            columns.Bound(o => o.FirstName).Width(200);
            columns.Bound(o => o.LastName).Width(250);
            columns.Bound(o => o.Active).ClientTemplate("<input type='checkbox' disabled='disabled' name='Active' <#=Active? checked='checked' : '' #> />").Width(70).HtmlAttributes(new { style = "text-align:center" }); ;


        })
        .Pageable(pagerAction => pagerAction.PageSize(20))
        .Sortable()
        .Selectable()
        .Scrollable()
        .Groupable()
        .Filterable()
        .HtmlAttributes(new { style = "width:50%;" })
       )}


 </fieldset>  
       <br/>
       <div align="center">
        <table>
        <tr>
        <td>
            <button id="btnAdd" type="submit" style="height:40px;width:70px" ">Add</button>
            </td>
            <td>
            <button style="height:40px;width:70px" ">Edit</button>
            </td>
            <td>
            <button style="height:40px;width:70px" ">Delete</button>
            </td>
        </tr>
        </table>   
       </div>
  </div>     



    <script type="text/javascript">
        $(function () {
            $('#btnAdd').click(function () {
                $.ajax({
                    type: "POST",
                    data: $('form').serialize(),
                    url: '@Url.Action("CreateUser", "User")',
                    success: function (result) {
                        $('#cuscreate').html(result)
                    }
                });
            });

            return false; // <!-- That's the important bit 
        }); 
</script> 

感谢您的帮助,非常感激。

祝好, 库尔特


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接