2013-02-14 113 views
0

我正在開發一個用戶管理應用程序,我需要在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是顯示在一個單獨的頁面,而不是顯示一個對話框在客戶端屏幕上。

  2. 在TemData中存儲異常消息,返回RedirectToAction(「index」),並嘗試加載頁面加載Adduser.cshtml - 這裏的問題是JQuery對話框變爲空白。

  3. return Json {new success = true} - 問題是消息顯示的是單獨的頁面,沒有提供確切的錯誤消息。

  4. 返回內容(警報(errmessage)) - 警告消息正在顯示,但是當點擊ok按鈕顯示空白單獨頁面時。

  5. 試圖在Adduser.cshtml中使用Javascript調用模型方法 - 不確定調用添加用戶的模型方法。如果成功如何重定向客戶端屏幕將從Adduser.cshtml工作

請任何人都可以幫助我這一點。

[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"); 

    } 

回答

0

這不是你應該尋找的行動的變化。基本上你應該用ajax和回調方法發佈表單,你可以檢查'成功'或'錯誤',並從那裏自行顯示對話框。

你必須有一定的回調後,阿賈克斯完成,如:

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

爲了進一步擴展它,你可以從控制器發送郵件這樣的「錯誤| ERROR_MESSAGE」。這樣你就可以通過將'result'字符分割result.get_data()來檢查它是成功還是錯誤。並顯示你的消息。

+0

謝謝高拉夫我會試試這個,讓你知道。 – VVR147493 2013-02-14 12:47:44

+0

是的..我以前做過這個。如果您在執行此操作時遇到任何問題,請告訴我。 – gaurav 2013-02-14 12:49:13

+0

當我指定返回爲下面的行不能應用|運算符來輸入字符串和字符串。你可以讓我知道需要發送消息返回的格式Json(new {「error」| ex.Message},JsonRequestBehavior.AllowGet); – VVR147493 2013-02-14 13:43:08