MVC中的取消按钮

时间:2016-06-01 12:41:47

标签: javascript jquery asp.net-mvc

我在表单中有一个面板,其中有3个按钮保存,编辑和取消 当用户单击编辑时,面板内的标签将更改为文本框,其中用户可以编辑内容。这部分完成了 现在,如果用户编辑了内容,但又不想保存,则单击取消。当他这样做时,编辑的文本将替换为标签的原始内容(数据来自模型) 我已按照here

给出的接受答案

控制器:

[HttpPost]
    public ActionResult Submit(int id, string actionType)
    {
        var model = new CustomerDetailsViewModel();
        var custid = db.Customers.Find(id);
        if(actionType == "Cancel")
        {
            model.Company = custid.Company;
            model.Address = custid.Address;
            model.FullName = custid.FirstName + " " + custid.LastName;
            model.EMail = custid.EMail;
            model.Phone = custid.Phone;
            model.EntryDate = custid.EntryDate;
            model.LastInterestShown = custid.LastInterestShown;
            model.ID = custid.ID;
            model.Status = custid.Status;
        }
        return PartialView(model);
    }

查看:

<input type="submit" value="Cancel" id="btncancel" name="actionType" class="btn btn-default" />

JS:

        $("#btnCancel").click(function(e){
        e.preventDefault();
        $.ajax({
            url: '/Client/Submit',
            type: 'POST',
            async: false
    });
});

有人能告诉我哪里出错了吗?

2 个答案:

答案 0 :(得分:0)

您正在发送一个类型为“GET”的ajax请求,并发送到url:“/ Client / Cancel”

如果你没有单独的

public ActionResult Cancel() {...}
控制器中的

字段,此ajax不起作用。

您需要做的是;

var postdata = { "id": id-here, "actionType": actionType-here  };

$("#btnCancel").click(function(e){
        e.preventDefault();
        $.ajax({
            url: '/Client/Submit',
            type: 'POST',
            data: JSON.stringfy(postdata),
            async: false
    });
});
在您的ClientController中

答案 1 :(得分:0)

您无需使用AJAX将输入字段重置为原始数据。假设您已将模型数据传递到视图,则可以使用隐藏输入来存储原始值,然后在用户单击取消按钮时将其取回(仅使用常规按钮)。

查看:

<input type="hidden" name="tempCompany" id="tempCompany" value="@Model.Company"> 
<input type="hidden" name="tempAddress" id="tempAddress" value="@Model.Address"> 
<input type="hidden" name="tempFullName" id="tempFullName" value="@Model.FullName">

JS:

<script>
    $("#btnCancel").click(function (e) {
        $('#Company').val($('#tempCompany').val());
        $('#Address').val($('#tempAddress').val());
        $('#FullName').val($('#tempFullName').val());
    });    
</script>