In C# can we check if a duplicate value is entered - c#

I have a grid view where I'm trying to insert a new value. Before doing an insert need to check if the value entered already exists in DB (cannot be duplicate).
The column that needs to be checked for duplicate is of type varchar which can accept maximum characters in a string (it can have spaces and can also have other special characters - it is basically a sentence).
E.g. Insert specific job-related impacts: (for example, impacts to customer or client service)
We cannot make this column unique in SQL server as it is declared as varchar(max).
Can we perform a check for a large string like this from C#?

The primary concept is as follows:
private void dataGridView1_CellValueChanged_1(object sender, DataGridViewCellEventArgs e)
{
int columnToCheck = 0;//The index of the property/field/column you want to check
if (e.ColumnIndex == columnToCheck)
{
using (var DB = new DataContext())
{
if (DB.YourTable.Where(v => v.id == dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()).Count > 0)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
MessageBox.Show("This key already exists");
//Return the error message to your javascript in asp.net here
}
}
}
}
In a website however, you'd have to make an ajax call, so whichever datatable you're using, find its event which would similar to dataGridView's CellValueChanged event. If you fail to do so, try adding the onchanged="" tag to its HTML element definition e.g. <table class="table" id="tab" onchanged="eventfunction(this)"></table> and in your javascript, handle the call like the following:
function eventfunction(element)
{
//Use an ajax call to your controller from here
var id = document.getElementById(element.id).innerText; //or however you can obtain the active cells' value
$.ajax({
url: "/api/ControllerName/ActionName",
method: "POST",
data: id,
success: function (response)
{
//Handle the return call here
},
error: function (response)
{
//Or here if you return an error message
}
});
}
Or you can use jQuery's event handling like this:
$("#tab").on("onchange", function()
{
//Your code here
});
You controller can look like this:
[HttpPost]
public Customer GetCustomer(string id)
{
//LINQ Where validation here
}

Related

Use an "If this already exists in the API" type statement

I have an API that I've created. I've (finally) managed to both GET and POST with it. Now I want to check the POST before it gets submitted.
I have a class with properties (is that the right word? I'm still learning the lingo) of id, name, city, state, and country.
I have a form with a button, and the button has a click event method that looks like this:
protected void submitButton_Click(object sender, EventArgs e)
{
void Add_Site(string n, string ci, string s, string co)
{
using (var client = new HttpClient())
{
site a = new site
{
name = n,
city = ci,
state = s,
country = co
};
var response = client.PostAsJsonAsync("api/site", a).Result;
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
else
Console.Write("Error");
}
}
Add_Site(nameText.Text, cityText.Text, stateText.Text, countryText.Text);
}
Now, at this point, it's working as expected. However, I'd like to limit it.
What I want to do is to have it look at the nameText.Text value. Before it runs the POST statement, I want it to look at the other values in the GET of the API and make sure that name doesn't already exist.
While I know that I could probably update the database to make the name field unique, I'd rather do it programatically in C#.
Is this something that's possible within my C# code? If so, what function would I use and how would I get it to return the Site.Name attribute to compare my nameText.Text value?
EDIT:
Here is the code for the POST as requested in one of the comments. Note: This was auto-generated by Visual Studio when I added the controller.
// POST: api/site
[ResponseType(typeof(site))]
public IHttpActionResult Postsite(site site)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.site.Add(site);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = site.id }, site);
}
I wouldn't have any idea where to even start with adding an "If the name already exists, throw an error," so some kind of walkthrough is plenty.
Here's code for looking in the database if any sites have the provided name (site.Name):
if (db.site.Any(o => o.Name == site.Name))
return BadRequest("Name already exists.");
I eventually determined that I should modify the POST as said in the comments. The solution I used ended up in this question: How to limit POST in web API

How to display different values without refreshing the page MVC C#

I have a method that is looping through a list of values, what I would like to do is when I open the page to be able to see the values changing without refreshing the current view. I've tried something like the code bellow.
public static int myValueReader { get; set; }
public static void ValueGenerator()
{
foreach (var item in myList)
{
myValue = item;
Thread.Sleep(1000);
}
}
The actual thing is I want it to read this values even if I close the form. I presume I would need to assign a Task in order to do this, but I was wandering if there is any better way of doing it since it's a MVC application?
Here's another way to do it:
use AJAX and setTimeout
declare one action in your controller (this one will return your different values)
an integer in your ViewBag, some like: ViewBag.totalItems
Declare an action in your controller: This is important, because this will be your connection with your database, or data. This action will receive the itemIndex and will return that item. Something like this:
[HttpPost]
public JsonResult GetItem(int index) {
return Json(myList.ElementAt(index));
}
ViewBag.TotalItems: Your view has to know how many Items you have in your list. I recommend you to pass that value as an integer via ViewBag:
public ActionResult Index() {
ViewBag.TotalItems = myList.Count();
return View();
}
AJAX and setTimeout: Once that you have all of this, you're ready to update your view without refreshing:
<script>
$(function() {
var totalItems = #Html.Raw(Json.Encode(ViewBag.TotalItems));
var currentItemIndex = 0;
var getData = function() {
$.post("#Url.Action("GetItem")", {index:currentItemIndex}, function(data) {
// data is myList.ElementAt(index)
// do something with it
}).always(function() {
currentItemIndex++;
if(currentItemIndex < totalItems) {
setTimeout(getData, 1000); // get the next item every 1 sec
}
})
}
getData(); // start updating
})
</script>
Your best bet as #DavidTansey mentioned is to use SignlarR. It wraps web sockets and falls back to long polling/etc if the users' browser doesn't support it. Your users will subscribe to specific channels and then you can raise events in those channels.
With regard to your business logic, you'll need to look into async programming techniques. Once you start on this, you'll probably have more specific questions.

Not waiting for Javascript function respone from code behind

Hi I have a scenario,
I have a list I need to save that into table before saving that I need to check that already exist or not if exist I need to show dialog to user Are you sure need to override (YES Or NO).these thing I need to do in code behind in web. before getting response(Yes or No) from user I need to wait if yes need to execute one function otherwise no execution.
I do the following in Code behind:
int dupCount = checkdup(id);
// Get Conformation From the User Need to Save OR Not
if (dupCount > 0){
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "confirm", "<script>Confirm();</script>", false);
Thread.Sleep(8000);
string confirmValue = hdnConform.Value;
if (confirmValue == "Yes"){
savemethod();
}
else { }
}
else{
savemethod();
}
In the design, I do this:
function Confirm() {
if (confirm("Do you want to save data?")) {
document.getElementById('<%=hdnConform.ClientID %>').value = "Yes";
} else {
document.getElementById('<%=hdnConform.ClientID %>').value = "No";
}
}
Now I come to the issue. While executing this, my javescript function is called very last and my code does't wait for user response (Yes or No), it is executing continually.
I suggest you a refactor of your code in this way. Call server side function only if the user wants to save data.
function Confirm() {
if (confirm("Do you want to save data?")) {
$.ajax({
url: 'your method url',
type: "POST",
//other parameters
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
} else {
//other code
}
}
I think that Thread.Sleep for this purpose is unuseful

Passing prompt box value from javascript function- PostBack to c#

I'll try to do the best I can to articulate what I'm trying to do.
Let me preface by saying that I am very new to C# and ASP.NET and have minimal experience with javascript.
I have a javascript function that invokes a prompt box. The overall picture is - if input is entered - it will be saved to a column in the database.
I'm drawing a blank on passing the value from the prompt box to the PostBack in c#.
function newName()
{
var nName = prompt("New Name", " ");
if (nName != null)
{
if (nName == " ")
{
alert("You have to specify the new name.");
return false;
}
else
{
// i think i need to getElementByID here???
//document.forms[0].submit();
}
}
}
This is what I have in C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//I have other code that works here
}
else
{
//I'm totally lost here
}
}
I'm trying to figure out how to make that call for the input from the javascript function.
I've spent the last few hours looking online and in books. Been overwhelmed.
EDIT
i did a little tweeking to fit what I'm trying to do....
<asp:HiddenField ID="txtAction" runat="server" Value="" />
document.forms(0).txtAction.Value = "saveevent";
document.forms(0).submit();
trying to figure out how to insert the string into the table now.....
string nEvent = Request.Form["event"];
if (txtAction.Value == "saveevent") {
nName.Insert(); //am i on the right track?
}
Well, here's one possible way (untested but should give you the basic idea). You could place a hidden field on your form to hold the value of the prompt:
<input type="hidden" id="hiddenNameField" runat="server" value="">
Then prompt the user for the value, set it to the hidden field, and then submit your form:
document.getElementById('hiddenNameField').value = nName;
document.forms(0).submit();
Then in your code-behind you can just access hiddenNameField.Value.
if you are trying to call the method on the back side using the java script you can try using the web method approach.
for instance you have a function that will call the SendForm method
function SendForm() {
var name = $("#label").text();
PageMethods.SendForm(name,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
}
function OnFailed(error) {
}
and you have the method that will be called from javascript.
[WebMethod(enableSession: true)]
public static void SendForm(string name)
{
}
<script language='Javascript'>
__doPostBack('__Page', '');
</script>
Copied from Postback using javascript
I think you need AJAX request here. I suggest usage of jQuery, since do the dogs work for you... Otherwise, you will have to implement a lot of already written general code for AJAX processing.
Something as the following one:
function PromptSomewhere(/* some args if needed*/)
{
var nName = prompt("New Name", " ");
// Do process your prompt here... as your code in JS above. Not placed here to be more readable.
// nName is used below in the AJAX request as a data field to be passed.
$.ajax({
type: "post", // may be get, put, delete also
url: 'place-the-url-to-the-page',
data {
name: nName
// You may put also other data
},
dataType: "json",
error: PromptFailed,
success: OnPromptComplete
});
}
function PromptFailed(xhr, txtStatus, thrownErr) // The arguments may be skipped, if you don't need them
{
// Request error handling and reporting here (404, 500, etc.), for example:
alert('Some error text...'); // or
alery(txtStatus); // etc.
}
function OnPromptComplete(res)
{
if(!res)
return;
if(res.code < 0)
{
// display some validation errors
return false;
}
// display success dialog, message, or whatever you want
$("div.status").html(result.message);
}
This will enable you to send dynamically data to the server with asynchronous request. Now C#:
using System.Web.Script.Serialization;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string nName = Request.Form["name"];
// do validation and storage of accepted value
// prepare your result object with values
result.code = some code for status on the other side
result.message = 'Some descriptive message to be shown on the page';
// return json result
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(result));
}
}
Notes: If you use ASP.NET MVC 2 or higher I think, you will be able to use JsonResult actions and Request.IsAjaxRequest (I think was the name), and many other facilities and improvements of ASP.NET - ASP.NET MVC is the new approach for creating web applications based on MVC pattern (architecture) and will replace ASP.NET Pages eventually in some time.
This is a very good resource and contains the answer to your question:
How to use __doPostBack()
Basically, call PostbackWithParameter() function from your other JS function:
<script type="text/javascript">
function PostbackWithParameter(parameter)
{
__doPostBack(null, parameter)
}
</script>
And in your code-behind, grab the value for that parameter like so:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
}

Dynamically search database and show results using Javascript and C#

I want to search a database for a clientName and dynamically show the results while the user is typing so they can select a User. It is now my understanding that this cannot be done without using javascript.
So if the user is typing "Al" then reults of clients called "Allan, Alison, Ali..." etc would show in a dropdownlist like display under it.
At the moment the user is entering the Clients name into a Textbox.
I know that creating the DropDownList should be done something like this:
private void InitializeNameDropDown(DataTable dtTable)
{
string ClientName = Clienttb.Text;
MySqlDataReader Reader = MySQLQuery(ClientName);
int nTotalRecords = dtTable.Rows.Count;
for (int i = 0; i < nTotalRecords; i++)
{
NameDropDown.Items.Add(dtTable.Rows[i]["Client"].ToString());
}
}
MySQLQuery() just checks that the client exists within the database.
But I don't know how to dynamically interact with the database to return the results as the user is typing.
Any Help will be appreciated, Thank you in advance.
You can do it without JS, hang event on text change on TextBox (OnTextChanged), and in there update DDL ( dont forget to set AutoPostBack=true ).
But it can easily make user wait ( "freeze page" ), or even rollback what he wrote if you are using Ajax.NET
I strongly recommend using JS rather then this ( use JS and WCF/ashx/regular WS, any of these will do ) due to performance gain and much better possibilities of customization.
ASP anyway generates a load of JS for "ASP controls".
This can be applied for example http://www.codeproject.com/KB/aspnet/Cross_Domain_Call.aspx
You'll have to hook into the keyup event on the text box and fire an XmlHttpRequest from that event - if you're using jQuery it's pretty simple:
$('#mytextbox').keyup(function() { $.ajax(blah blah) });
Alternatively, as Dennis says, just use the auto-complete plugin - it's very simple and works well.
As for the client side try jquery and jqueryui's autocomplete, it's just a suggestion, jquery has a nice ajax call and it's really simple to use, and for the jqueryui autocomplete, you just pass it keywords and it will create a list right under the input box.
http://jquery.com/
http://jqueryui.com/
http://api.jquery.com/jQuery.ajax/
Here's some code that might get you going.
It uses the jquery Javascript library. It assumes you're getting the full HTML of the results list that you want to display to the user. You'll need more Javascript to dynamically show/hide the box that contains the list. You'll also need a server-side script that gets a collection of search results based on some search text. That script should be located at the URL defined in the #searchPartialUrl tag (which can be hidden). The search text should be in an input called #searchText.
I like this method because you can maintain your JS code in a separate file and reuse it. Your server just needs to create HTML views that have all the async target information in regular HTML tags.
I also implemented a delay between checking key-events so that you're not constantly sending requests to your server. (I got this method from another answer on stackoverflow, but I can't seem to find it now. I'll give credit when I do.)
// This function is used to delay the async request of search results
// so we're not constantly sending requests.
var mydelay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
var asyncSearchForm = function(onSuccess) {
var keyupWrapper = function(keyCode) {
// if this key was an arrow key, then
// ignore the press
for (var i = 37; i <= 40; i++)
if (keyCode == i)
return;
// get all the search info from the form
var searchText = $('#searchText').val();
var searchPartialUrl = $('#searchPartialUrl').val();
// make the ajax call
$.ajax({
type: "POST",
url: searchPartialUrl,
data: {
searchText: searchText
},
dataType: "html",
// on success, the entire results content should be replaced
// by the results returned
success: function(data, textStatus, jqXHR) {
$('#searchResults').html(data);
onSuccess();
},
// on error, replace the results with an error message
error: function(jqXHR, textStatus, errorThrown) {
$('#searchResults').html('<p>An error occurred while getting the search results.</p>');
}
});
};
onSuccess = (typeof (onSuccess) == 'undefined') ? function() { } : onSuccess;
// On each key-up event, we'll search for the given input. This event
// will only get triggered according to the delay given, so it isn't
// called constantly (which wouldn't be a good idea).
$('#searchText').keyup(function(e) {
// delay between each event
mydelay(function() {
// call key up
keyupWrapper(e.keyCode);
}, 500);
});
}
Update:
You said you're using C#. If you're using MVC, you'll need an action in your controller to be a target for your async request. Here's an example:
[HttpPost]
public ActionResult GetSearchResults(string searchText)
{
// Here, you should query your database for results based
// on the given search text. Then, you can create a view
// using those results and send it back to the client.
var model = GetSearchResultsModel(searchText);
return View(model);
}

Categories