从控制器显示警报

时间:2013-02-14 12:23:56

标签: jquery json jquery-ui asp.net-mvc-4

我正在开发一个用户管理应用程序,我需要在db中添加用户。

When click of a button in client screen ( index.cshtml ), a JQuery dialog will popup and fill the user details ( Adduser.cshtml (partial class) ) . On click of Save button the data will pass to controller validate it and call the model method to add the user. If the user already exists the webservice will return error message. In controller the exception will be catched and wants to show it to user.

在异常之后我需要将错误消息显示为警报或将其写在AddUser.cshtml上。以下是我尝试过的各种选项以及

的问题
  1. 返回部分(" AddUser",型号) - 这里的问题是Adduser.cshtml显示在单独的页面中,而不是在客户端屏幕中显示为对话框。

    < / LI>
  2. 在TemData中存储异常消息,返回RedirectToAction(&#34;索引&#34;)并尝试在页面加载时加载Adduser.cshtml - 这里的问题是JQuery对话框变为空白。

  3. 返回Json {new success = true} - 问题是消息显示单独的页面而没有给出确切的错误消息。

  4. 返回内容(警告(错误消息)) - 显示警告消息但单击确定按钮显示空白的单独页面时。

  5. 尝试在Adduser.cshtml中使用Javascript调用模型方法 - 不确定调用模型方法来添加用户。如果成功如何从Adduser.cshtml

  6. 重定向到客户端屏幕

    请允许任何人帮助我。

        [HttpPost]
        public ActionResult AddClient(ClientModel mCust, string command)
        {
            var clientObj = new Metadata.Client.Service.Client();
            ClientModel clientModel = new ClientModel();
    
            if (command == "Save")
            {
    
                if (!ModelState.IsValid)
                {
                    return PartialView(mCust);
                }
    
    
                clientObj.ClientType = new Metadata.Client.Service.ClientType();
                clientObj.ClientName = mCust.Client.ClientName;
                clientObj.ClientCode = mCust.Client.ClientCode;
                if (mCust.ClientTypeSelectId != 0)
                    clientObj.ClientType.ClientTypeId = (mCust.ClientTypeSelectId) - 1;
                else
                    clientObj.ClientType.ClientTypeId = mCust.ClientTypeSelectId;
    
                try
                {
                    clientObj = clientModel.AddNewClient(clientObj);
                }
                catch (Exception ex)
                {
                    //TempData["addclient"] = null;
                    //TempData["addclient"] = ex.Message;
                    //mCust.SetClientTypeList();
                    //mCust.WebResponse.Message = ex.Message;
                    //return PartialView(mCust);
    
                    // we're gonna show this in a ValidationSummary
                    ModelState.AddModelError("", ex.Message);
                    return PartialView("AddClient", mCust);
    
                }
            }
    
            return RedirectToAction("Index");
    
        }
    

1 个答案:

答案 0 :(得分:0)

这不是你应该寻找的行动变化。基本上您应该使用ajax发布表单,并且在回调方法上,您可以检查“成功”或“错误”并从中自动显示对话框。

你必须在ajax完成之后进行一些回调,如:

<script type='text/javascript'>
function onSuccess(result){if(result.get_data()=='error'){alert('error'); }}
</script>

为了进一步扩展,您可以从控制器发送消息,如“error | error_message”。这样你可以通过将result.get_data()除以字符'|'来检查它是成功还是错误并显示您传递的消息。