Reputation: 195
I want to generate a random 3 digit string in MVC3-Razor-C#.net. But condition is that, before generating random string, i need to check in database i.e. SQL 2008 whether this record is already present or not. If the random generated string is already present in database I need to generate new string. This functionality is for a button called "NextAvailable". I was able to generate random string using JavaScript, but not able to check in database if it is already exists. It would be great if any help me out for this.
Here is my Javascript function which is working fine, but how to check database using AJAX for existence of a string.
function btnNextAvailable_OnClick() {
$("#nextAvailableButtonClick.val('true')");
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
}
Upvotes: 0
Views: 2593
Reputation: 151672
You could implement it like this:
MVC:
public class RandomNumberController : Controller
// Or take a look at ApiController
{
public ActionResult GetRandomNumber()
{
string number = new RandomNumberGenerator().GetNextFreeRandomNumber();
return Json(new { number = number}, JsonRequestBehavior.AllowGet);
}
}
Database logic:
public class RandomNumberGenerator
{
public string GetNextFreeRandomNumber()
{
// do database calls, return next free random number
return "042";
}
}
Now from your webpage, you can do something like this:
$.get('/RandomNumber/GetRandomNumber', function(data) {
alert(data.number);
});
You simply do not want your client to keep hammering the service until the service returns a valid number, so you do the number generation on the server.
Now if you have a problem implementing a specific part of this, feel free to update your question.
Upvotes: 2