1

在 MVC-3 (Razor Engine) 中:我想在单击按钮时生成随机字符串NextAvailable,但条件是在生成随机字符串之前查看 SQL 数据库是否已经生成。如果数据库中已经存在,则生成一个新字符串。任何人都可以帮助我...这是我生成随机字符串的代码:

 <script type="text/javascript"> 
    function btnNextAvailable_OnClick() { 
     $("#nextAvailableButtonClick.val('true')"); 
     var mode = $.hash.getValue("m"); 
     var chars = "0123456789"; 
     var stringLength = 3; 
     var randomstring = ''; 
     for (var i = 0; i < stringLength; i++) { 
      var rnum = Math.floor(Math.random() * chars.length); 
      randomstring += chars.substring(rnum, rnum + 1); 
     } 
     document.getElementById("SequentialId").value = randomstring 
    }
</script> 
4

1 回答 1

1
  function btnNextAvailable_OnClick() { 
        var randomstring=GenerateRandonString();
        while(IsRandomStringExists(randomstring))
        {
            document.getElementById("SequentialId").value = randomstring 
        }

        document.getElementById("SequentialId").value = randomstring 
    }
 function IsRandomStringExists(randomstring)
 {
   $.get('Home/CheckStringExists/'+randomstring  ,function(response)
     {

        if(response=="true")
            {
               return true;
            }else
           {
              return false;
           }
      });
   }
     function GenerateRandonString()
      {
        $("#nextAvailableButtonClick.val('true')"); 
        var mode = $.hash.getValue("m"); 
        var chars = "0123456789"; 
        var stringLength = 3; 
        var randomstring = ''; 
        for (var i = 0; i < stringLength; i++) { 
        var rnum = Math.floor(Math.random() * chars.length); 
        randomstring += chars.substring(rnum, rnum + 1); 
        return randomstring;
      } 

Also create "CheckStringExists" ActionMethod in Home controller or in your controller with parameter.

In HomeController

public JsonResult CheckStringExists(string id)
{
    //Write database logic here
    return Json((object)"true", JsonRequestBehavior.AllowGet);
}

In HomeController

public JsonResult CheckStringExists(string id)
{           
    var customer = ObjectContext.Companies.OfType<TrueTracEntities.Customer>().Where(r =>  r.SequentialId.Equals(id)).FirstOrDefault();      
    return Json((object)"true", JsonRequestBehavior.AllowGet);
}
于 2013-06-04T07:30:53.297 回答