Как заставить DateTextBox (dojo) по-прежнему отображать недопустимую дату значения после отправки экрана? - PullRequest
0 голосов
/ 17 мая 2011

Я использую DateTextBox из библиотеки dojo на моей веб-странице. После ввода неверного значения вручную в DateTextbox и отправки экрана это значение исчезает :(. Моя идея - продолжать показывать это значение, чтобы пользователи могли видеть, какое неправильное значение они ввели. Как я могу это сделать?

Любая помощь высоко ценится,

Заранее спасибо:)

Ответы [ 3 ]

0 голосов
/ 18 мая 2011

спасибо за ваш ответ и комментарии.Я думаю, что вы должны сделать, чтобы создать новое всплывающее окно для хранения сообщения «Недопустимая дата» после нажатия кнопки «Отправить».Так же, как я сделал в своем примере, я создаю класс с именем AlMessageBox.Show (это «Недопустимая дата»).как только я отредактирую дату, скажем «5/32/2011», а затем отправлю, должно появиться всплывающее окно «Недопустимая дата», затем, когда я нажимаю «ОК», дата, которую я ввел «32.05.2011», все еще там.

0 голосов
/ 19 мая 2011

enter image description here Привет, Юги, извините за то, что я никогда не пробую виджет додзё. Что я сделал на своей веб-странице, чтобы получить запись даты, так это то, что я использую AjaxControlToolkit для фильтрации допустимых символов ввода, которые указываются в текстовом поле моей даты.
Если вы хотите попробовать это, вы можете загрузить AjaxControlToolkit, с которым следует Версия файла: 3.0.20229.0

, из поиска Google.

Вам следует обратиться к файлу AjaxControlToolkit.dll в вашем решении.проект.затем зарегистрируйте его:

См. код клиента ViewProcessedClaims.aspx.cs

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewProcessedClaims.aspx.cs"
    Inherits="MedilinkSites.ViewProcessedClaims" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

Затем в теге Body: Пример:

<tr>
     <td>
          <asp:TextBox ID="txtDateFrom" runat="server" Width="70px" OnTextChanged="txtDateFrom_TextChanged"></asp:TextBox>
          <cc1:CalendarExtender PopupButtonID="ImageDatePicker" ID="CalFrom" TargetControlID="txtDateFrom"
             runat="server">
          </cc1:CalendarExtender>
          <cc1:FilteredTextBoxExtender ID="ftDateFrom" ValidChars="1234567890/" TargetControlID="txtDateFrom"
             runat="server">
          </cc1:FilteredTextBoxExtender>
             &nbsp;<asp:ImageButton ID="ImageDatePicker" runat="server" ImageUrl="images/Calendar.png"
             AlternateText="Click here to display calendar" Height="16px" />
      </td>
</tr>

В отправке button_click:

string dateFrom = this.txtDateFrom.Text;
if (!IsValidDate( dateFrom))  // Calling my previous function IsValidDate()
{
    AlMessageBox.Show(this, "Invalide Date");    // Calling my prev. pop-up message box
    this.txtDateFrom.Focus();
    return;
}

Примечание: просто включите мой предыдущий код, который я сделал ...

Надеюсь, это может помочь ... С уважением,

0 голосов
/ 17 мая 2011

См. Этот простой код в C #, если когда-либо мог помочь вам.

//// In your code-behind:
//// String formate should ‘mm/dd/yyyy’
 if (!IsValidDate( dateFrom))
 {
     AlMessageBox.Show(this, "Invalide Date");
     this.txtDateFrom.Focus();
     return;
 }

 Proceed....
 .....

// String formate should ‘mm/dd/yyyy’
public static Boolean IsValidDate(string date)
{
  bool retValue = true;
  if (date == string.Empty)
  {
        return false;
  }
  if ((date.Split(‘/’).Length – 1) != 2) // Count the occurence of ‘/’ should be 2
  {
        return false;
  }

  int mon = date.Split(‘/’)[0].ToInt();
  int day = date.Split(‘/’)[1].ToInt(); 
  int yr = date.Split(‘/’)[2].ToInt();

  if (mon > 12 || mon == 0) // Validate month
  {
        return false;
  }
  int daysLimitInMonth = GetDaysInMonth(mon); 

  if (day > daysLimitInMonth || day == 0 )
  { 
        return false;
  }

  if (yr < 1000 ) // Bellow 1000 years is not invalid
  { 
        return false;
  }

  return retValue;
}

private static int GetDaysInMonth(int mon)
{
    int daysLimitInMonth = 31;

    switch (mon)
    { 
    case 2: // case month is Feb 
        if (IsLeapYear(mon)) // determine the year if is Leap Year
           daysLimitInMonth = 29;
        else
            daysLimitInMonth = 28;
        break;

    case 4: // April
        daysLimitInMonth = 30;
    case 6: // June
         daysLimitInMonth = 30;
    case 9: // Sept
         daysLimitInMonth = 30;
    case 11: // Nov
        daysLimitInMonth = 30;

    default:
        daysLimitInMonth = 31;
        break;
   }
   return daysLimitInMonth;
}

private static bool IsLeapYear(int year)
{
    if ((year % 400) == 0)
        return true;
    if ((year % 100) == 0)
        return false;
    if ((year % 4) == 0)
        return true;
    return false;
}

public class AlMessageBox
{
   private static Hashtable m_executingPages = new Hashtable();
   private MessageBox() { }
   public static void Show(string sMessage)
   {
      // If this is the first time a page has called this method then
      if (!m_executingPages.Contains(HttpContext.Current.Handler))
      {
         // Attempt to cast HttpHandler as a Page.
         Page executingPage = HttpContext.Current.Handler as Page;
         if (executingPage != null)
         {
            // Create a Queue to hold one or more messages.
            Queue messageQueue = new Queue();
            // Add our message to the Queue
            messageQueue.Enqueue(sMessage);
            // Add our message queue to the hash table. Use our page reference
            // (IHttpHandler) as the key.
            m_executingPages.Add(HttpContext.Current.Handler, messageQueue);
            // Wire up Unload event so that we can inject 
            // some JavaScript for the alerts.
            executingPage.Unload += new EventHandler(ExecutingPage_Unload);
         }
     }
     else
     {
         // If were here then the method has allready been 
         Queue queue = (Queue)m_executingPages[HttpContext.Current.Handler];
         // Add our message to the Queue
         queue.Enqueue(sMessage);
      }
 }

 public static void Show(System.Web.UI.Page page, string msg)
 {
     ScriptManager.RegisterClientScriptBlock(page, page.GetType(), 
     "clientScript", "javascript:alert('" + msg + "');", true);
 }

 private static void ExecutingPage_Unload(object sender, EventArgs e)
 {
     // Get our message queue from the hashtable
     Queue queue = (Queue)m_executingPages[HttpContext.Current.Handler];
     if (queue != null)
     {
        StringBuilder sb = new StringBuilder();
        // How many messages have been registered?
        int iMsgCount = queue.Count;
        // Use StringBuilder to build up our client slide JavaScript.
        sb.Append("<script language='javascript'>");
        // Loop round registered messages
        string sMsg;
        while (iMsgCount-- > 0)
        {
            sMsg = (string)queue.Dequeue();
            sMsg = sMsg.Replace("\n", "\\n");
            sMsg = sMsg.Replace("\"", "'");
            sb.Append(@"alert( """ + sMsg + @""" );");
        }
        // Close our JS
        sb.Append(@"</script>");
        // Were done, so remove our page reference from the hashtable
        m_executingPages.Remove(HttpContext.Current.Handler);
        // Write the JavaScript to the end of the response stream.
        HttpContext.Current.Response.Write(sb.ToString());
        }
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...