1

In MVC-3 (Razor Engine) : I want to generate random string on a button click called NextAvailable, but condition is that before generation of random string look into SQL database that it is already generated or not. If already present in database, then generate a new string. Can anybody please help me... Here is my code for generating randon string:

 <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> 
Roar
  • 2,117
  • 4
  • 24
  • 39
user2450398
  • 175
  • 1
  • 7
  • 16

1 Answers1

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);
}
Glitch Desire
  • 14,632
  • 7
  • 43
  • 55
Khalid
  • 194
  • 4
  • Hi Khalid, Thanks for your quick response. Can you please help me out how to code for ActionResult in my Home controller by passing parameters. I am very much new for MVC3. – user2450398 Jun 04 '13 at 09:21