Save Form data in database - c#

I am trying to get the selected radio button value to from html to server side so that i can save them in the data base i have done similar in php not sure how to do that in asp.net/ C#
<form runat="server" id='attendence_form' >
<table id="attendence_div" width="100%" align="center" cellpadding="2" cellspacing="2" border="0">
<tr align="left" style="background-color:#004080;color:White;">
<td>Student Name</td>
<td>Present</td>
<td>Absent</td>
<td>Leave</td>
</tr>
<tr>
<td>ANITHA S</td>
<td><input type="radio" name="Present0" value="Present"></td>
<td><input type="radio" name="Present0" value="Absent"></td>
<td><input type="radio" name="Present0" value="Leave"></td>
</tr>
<tr>
<td>ANITHA T C</td>
<td><input type="radio" name="Present1" value="Present"></td>
<td><input type="radio" name="Present1" value="Absent"></td>
<td><input type="radio" name="Present1" value="Leave"></td>
</tr>
<tr>
<td>BINDU K V</td>
<td><input type="radio" name="Present2" value="Present"></td>
<td><input type="radio" name="Present2" value="Absent"></td>
<td><input type="radio" name="Present2" value="Leave"></td>
</tr>
</table>
Hear is the php code this recives the html form values form the user side via ajax and insert i want the same in asp.net
$conn = new mysqli($servername, $username, $password, $dbname);
// ** insert data in to data base ** //
$sql = "INSERT INTO attendance_master (AttendanceDate) VALUES ";
// **hear the data or is calculated using student as a string the number of student names are passed the same number of data is inserted in to data base ** //
foreach($_GET['student'] as $i=>$student) {
// ** so the data is inserted in to data base ** //
$sql .= sprintf("%s ('%s')"
, ($i==0 ? '' : ',')
// ** data from Ajax ** //
, mysqli_real_escape_string($conn, trim($_GET['present'][$i]))
);
}
// ** on success full function ** //
if ($conn->query($sql)) {
// **can do any thing to recognise if the data is inserted if this gives the out put then the data is shorly inserted in to data base ** //
}

you can try using <asp: RadioButton id="" runat="server" > .
In the server side you can check the "Checked" property like this
if(radioBtn.Checked==true) {}

If it is a webforms project you should use
<asp:RadioButton id="someId" runat="server">
Update:
To handle when the radiobutton is clicked you need to handle the CheckedChanged event.
someId.CheckedChanged += event_CheckedChanged;
private void event_CheckedChanged(Object sender, EventArgs e)
{
... do stuff...
}

Related

Blazor List Of Strings Input Binding

I'm trying to display a list of strings and I want the user to be able to edit the list to make changes to the object but when I view the list after modifying the input fields the changes haven't been made.
How do I bind a list of strings?
#foreach (var message in UserMessageService.GetSomeData())
{
<tr>
<td><input type="text" bind="#message.Username" value="#message.Username" onblur="SaveMessages"/></td>
<td><input type="text" bind="#message.Message" value="#message.Message" onblur="SaveMessages"/></td>
</tr>
}
Use right Blazor syntax:
<input
type="text" #bind="#message.Message"/>
If you need to execute function on blur:
<input value="#message.Message"
#onchange="#((ChangeEventArgs __e) =>
{ message.Message = __e.Value.ToString());
SaveMessages(); })" />
More info: https://learn.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.0#data-binding
silly mistake on my part, the issue wasn't with my syntax. I made the mistake of binding to my service instead of a local variable so when I left focus it couldn't update and just retrieved from the service
I simply added the local variable below
#foreach (var message in dataVariable)
{
<tr>
<td><input type="text" #bind="message.Username" /></td>
<td><input type="text" #bind="message.Message" /></td>
</tr>
}
#code {
private List<someData> dataVariable;
protected override void OnInitialized()
{
TableSeats = UserMessageService.GetSomeData();
}
}

get values in controller class from html form elements with the same name

In my MVC project, I created a table from a database I made, and added Edit/Save and Delete buttons to interact with the DB accordingly.
I created the code in the cshtml file with razor-notation for loop, which means that my input elements all have the same name (to be called in the controller).
I'm trying to figure out how to single out a specific row and get a specific element, even though there are multiple elements with the same name (number of rows in my table).
snippet of my view:
#{
int i=0;
foreach(link l in Model.links)
{
<tr>
<td><input class="idField" name="link.Id" type="text" value="#l.Id" disabled="disabled" /></td>
<td><input class="linkField" name="link.link" type="text" value="#l.link" disabled="disabled" /></td>
<td><input class="timeField" name="link.Time" type="text" value="#l.Id" disabled="disabled" /></td>
<td>
<input class="edit" type="button" value="Edit" formaction="Update" onclick="enableField(#i)" />
</td>
</tr>
i++;
}
}
Update action in my controller:
public ActionResut Update(){
LinkDal dal = new LinkDal(); /*LinkDal uses Entity framework to connect to my DB*/
List<Link> links = dal.links.ToList<Link>();
Link toUpdate = dal.links.Find(int.Parse(Request.Form["link.Id"].ToString()));
toUpdate.link = Request.Form["link.link"].ToString();
toUpdate.Time = int.Parse(Request.Form["link.link"].ToString());
dal.SaveChanges();
VMLinks vml = new VMLinks();
vml.link = toUpdate;
vml.links = links;
return View("MyView", vml);
}
instead of gettin the specific "link" object, "toUpdate" becomes null because the Request.Form doesn't return anything.
I tried typing an ID that I know it exists and the code works (the DB is updated).
My problem is that I'm not being able to access the text inside the input element because there are multiple elements with the same name (for example - "link.Id").

How to get all value of all checked rows in table with FormCollection?

I have searched for help but can find any topic that could help me.
I have a table like this
<table id="tableftest" class="table table-striped table-vmiddle">
<thead>
<tr>
<th data-column-id="" data-sortable="false">
<input type="checkbox" id="checkall" title="chọn tất cả" onclick="" />
</th>
<th data-column-id="ip">IP</th>
<th data-column-id="network" hidden="hidden">Network</th>
<th data-column-id="sender">GateWay</th>
<th data-column-id="received">SubnetMask</th>
<th data-column-id="viewdetail">VPS được gán</th>
#*<th data-column-id="commands" data-formatter="commands" data-sortable="false"></th>*#
</tr>
</thead>
<tbody>
#foreach (VPSIP ipitem in ip)
{
<tr>
#if (ipitem.VPSID != null)
{
<td></td>
}
else
{
<td>
<input type="checkbox" class="ipDelListClass" name="ipDelList" value="#ipitem.IpID" />
</td>
}
<td>#(ipitem.IPAddress)</td>
<td hidden="hidden">#ipitem.NetworkRanx.NetworkAddress</td>
<td>#(ipitem.NetworkRanx.Gateway)</td>
<td>#ipitem.NetworkRanx.SubnetMask</td>
#if (ipitem.VPSID != null)
{
<td>#(ipitem.VPSs.VPSName)</td>
#*<td></td>*#
}
else
{
<td></td>
#*<td>
<button title="Xóa ip" class="btn btn-danger zmdi zmdi-delete" data-toggle="modal" data-target="#IpDel_#ipitem.IpID" style="font-size:medium"></button>
</td>*#
}
</tr>
}
</tbody>
</table>
When I check all checkboxs in table and click button delete, it will post data to this controller
[HttpPost]
public ActionResult IPDeleteMany(FormCollection f)
{
var ipDelArray = f.Get("ipDelList");
ServerBusiness serBu = new ServerBusiness();
string[] ipDelList = ipDelArray.Split(',');
try
{
foreach (string ipId in ipDelList)
{
var iprow = serBu.getIPById(int.Parse(ipId));
serBu.removeIPById(iprow);
}
TempData["Success"] = "IP đã bị xóa!";
return RedirectToAction("ViewListIP", "TechnicalStaff");
}
catch
{
TempData["Error"] = "Lỗi!";
return RedirectToAction("ViewListIP", "TechnicalStaff");
}
}
When it runs, it only get values of rows that is visible, not all the rows in table.
Is there anyway to get all of values checked in table include invisible rows?
change your hidden="hidden" to style="display:none;".
And for you other pages, because you didnt use Ajax your data isn't exist in fact, so you can:
use Ajax and hide your old rows and append new rows where exist
all of your desired rows in your html however some of them be
hidden.
force your users to submit current page data and then switch pages.

WebMatrix filling attribute and JavaScript Reading Attribute not producing expected results

I am having an issue with the following code:
SECTION FROM CSHTML FILE:
#if(errorMessage != "")
{
err="err";
}
else
{
err="";
}
#if(errorMessage == "")
{
foreach(var row in db.Query(stringCompiler, EntryID, POIName, DateLastModified, Gender, Race, Height, Weight, HairColor, EyeColor, DOB, Age, SS, DL, DOC, VehicleTag, FBI, Officer, HomePhone, CellPhone, CellPhone2, CellPhone3, POICautions, WorkPhone, WeightedAggregate, Address, AdditionalDescriptors, Aliases, SourceOfInformation, AddressInformation, KnownAssociates, VehicleDescription, Comments, SummarizedIncidents, AllCellPhones, AllPhones, betDOB1, betDOB2, betDLM1, betDLM2, betAge1, betAge2, POILastName, SearchAll))
{
<div class="searchResult">
<table style="background-color: #beebeb;">
<tr>
<td class="entryLabel">ENTRY ID</td>
<td class="entryLabel">FIRST NAME</td>
<td class="entryLabel">LAST NAME</td>
<td class="entryLabel">DATE LAST MODIFIED</td>
<td class="entryLabel">DOB</td>
<td class="entryLabel">AGE</td>
<td class="entryLabel">ADDRESS</td>
<td class="entryLabel">VEHICLE TAG#</td>
<td class="entryLabel">OFFICER</td>
<td class="entryLabel">HOME PHONE</td>
<td class="entryLabel">CELL PHONE</td>
<td class="entryLabel">WEIGHTED AGGREGATE</td>
</tr>
<tr>
<td class="entry">#row.EntryID</td>
<td class="entry">#row.POIName</td>
<td class="entry">#row.POILastName</td>
<td class="entry">#row.DateLastModified</td>
<td class="entry">#row.DOB</td>
<td class="entry">#row.Age</td>
<td class="entry">#row.Address</td>
<td class="entry">#row.VehicleTag</td>
<td class="entry">#row.Officer</td>
<td class="entry">#row.HomePhone</td>
<td class="entry">#row.CellPhone</td>
<td class="entry">#row.WeightedAggregate</td>
</tr>
<tr>
<td colspan="13" style="text-align: center;"><form method="post" action="/ComputeLookupToVAndE.cshtml"><input type="hidden" name="veEntryID" hidden="hidden" readonly="true" value="#row.EntryID" /><br/><input type="submit" value="View & Edit" class="btn3" style="height: 40px; width: 100px;" /><br/><br/></form></td>
</tr>
</table>
</div><br/>
ResultCount += 1;
}
<input type="hidden" id="ResultCount" value="#ResultCount" />
<input id="err" type="hidden" value='#err' />
}
SECTION FROM JAVASCRIPT FILE:
$(document).ready(function () {
if ($("#err").val() == "err")
{
$("#searchForm").attr('action', "/LookUpEntry.cshtml#top");
}
else
{
$("#searchForm").attr('action', "/LookUpEntry.cshtml#searchList");
}
});
Obviously I am trying to change the value of the hidden input element to "err" before the page is rendered by C# if any error messages have been stored in the variable errorMessage.
Once done JavaScript is supposed to read this value and then if it is "err" change the action attribute of the form to append "#top" (for named anchor, so the loaded position on the page changes based off of whether there is an error message or results to view), otherwise the form's action attribute should be changed (still by JavaScript) to append #searchList).
Any idea why JavaScript and C# won't play well together? The errors I am getting are haphazard (like it won't work the first time, then doesn't work at all), anyway based on the code below, it still never goes to (#top), although when trying a few things before this exact coding (I don't remember exactly what they were) it would sometimes (although never the first time) go to the top if it had errored.
Why is jQuery not doing its job? It seems like this should just work to me...
Any ideas?
Thanks for any help
Well, I guess I have it figured out and I suppose it does make sense:
It does change the value as it should, but the action (how the form [or rather where, the way I look at it] handles the data posted) is already set to what it where it will go regardless of the results of the current search. In short: It is a step behind. When I click to search and an error Message is produced, it will rewrite the action as intended, but it will, of course, only come into effect on the next search not the current one as that was already determined on the previous submit.
What's wrong with my code? Nothing syntactically, the methodology (logic) is in err.

RadioButtonList SelectedItem always returns EmptyString

I have this custom radiobuttonlist I'm using in my .aspx page in order to be able to get the GroupName to actually work since I will have 2 RadiobuttonList controls on the same .aspx page:
public class CustRadioButtonList : RadioButtonList, IRepeatInfoUser
{
void IRepeatInfoUser.RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
{
RadioButton radioButton = new RadioButton();
radioButton.Page = this.Page;
radioButton.GroupName = "radioButtonGroup";
radioButton.ID = this.ClientID + "_" + repeatIndex.ToString();
radioButton.Text = this.Items[repeatIndex].Text;
radioButton.Attributes["value"] = this.Items[repeatIndex].Value;
radioButton.Checked = this.Items[repeatIndex].Selected;
radioButton.TextAlign = this.TextAlign;
radioButton.AutoPostBack = this.AutoPostBack;
radioButton.TabIndex = this.TabIndex;
radioButton.Enabled = this.Enabled;
radioButton.RenderControl(writer);
}
}
So that's just a simple extentension where I set the GroupName to be sure that all the radiobuttons created by that RadioButtonList have the same GroupName so that now, if anyone selects a value from RadiobuttonList1, it deselects any value they have selected in Radiobutton2 and vice versa (so they are mutually exclusive sets of radiobuttons).
Note: The radiobuttonlists are definitely being binded via a method call that's wrapped in a check for !Page.IsPostBack so that is not the issue here.
Here is an example where I'm using it in my .aspx page:
<aj:CustRadioButtonList checked="false" ID="rblEmail" runat="server" />
<aj:CustRadioButtonList checked="false" ID="rblReason" runat="server" />
Here in my code-behind, I'm checking for the selectedValue from the rblEmail within an onclick even of a button on my page..but it always returns empty string even if I have selected an item in the list:
protected void btnContinue_Click(object sender, EventArgs e)
{
_actionID = rblEmail.SelectedValue;
I've spent an entire day around trying to figure out now why I keep getting an emptystring when clearly I have selected a value in rblEmail. Same holds true for the other radiobuttonlist rblReason. In either case, when checking from code-behind I get emptystring for SelectedValue.
If you look at the markup, here's how it looks:
<table id="rblEmail" checked="false" border="0">
<tr>
<td><input id="rblEmail_0" type="radio" name="radioButtonGroup" value="0" /><label for="rblEmai_0">All Offers</label></td>
</tr><tr>
<td><input id="rblEmail_1" type="radio" name="radioButtonGroup" value="1" /><label for="rblEmail_1">week</label></td>
</tr><tr>
<td><input id="rblEmail_2" type="radio" name="radioButtonGroup" value="2" /><label for="rblEmail_2">month</label></td>
</tr><tr>
<td><input id="rblEmail_3" type="radio" name="radioButtonGroup" value="3" /><label for="rblEmail_3">Holiday</label></td>
</tr>
</table>
</div>
...
<table id="rblReason" checked="false" border="0">
<tr>
<td><input id="rblReason_0" type="radio" name="radioButtonGroup" value="1" /><label for="rblReason_0">I receive</label></td>
</tr><tr>
<td><input id="rblReason_1" type="radio" name="radioButtonGroup" value="2" /><label for="rblReason_1">I have no need</label></td>
</tr><tr>
<td><input id="rblReason_2" type="radio" name="radioButtonGroup" value="3" /><label for="rblReason_2">Other</label></td>
</tr>
</table>
Don't know exactly why this isn't working, but it seems like a little javascript would provide an easy workaround. Instead of a custom control, just use regular RadioButton objects... then attach some javascript to clear the selection on List1 when something on List2 is selected, and vice versa.
Not sure why you'd use any sort of repeater here if you already know how many radiobuttons there would be? (per your comments above)
It seems that you're populating the RadioButtonList on the page load -
If so - make sure you surround your population of the RadioButtonList with an
If/Then/Postback block:
if not Page.IsPostBack then
' populate your RadioButtonList
end if
eg:
if (!IsPostBack)
{
loadradiobuttonlist();
}

Categories

Resources