.Net drop down menu c# - c#

I'm having and issue with passing a variable from page to page. Here I have a drop down menu that allows two options of Yes or No to be chosen. With the default of Choose.
<form method="post" id="Form" action="/admin/DefCon5">
<table align="center" style="width: 200px; height: 140px;">
<tr>
<td colspan="5"><img src="/images/logo.png"><br> </td>
</tr>
</table>
<div align="center">
<select id = "DefCon5" align="center" valign="top" name="DefCon5">
<option value="Choose">Choose..</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br />
&nbsp &nbsp &nbsp &nbsp &nbsp
<textarea align="Center" name="message" value="message" rows="4" cols="40">Please enter a brief message before engaging DefCon5</textarea>
<br />
<input type="submit">
</div>
Here I take one of those two options( for testing purposes I chose Yes)
string yes = Request.Params["Yes"];
string no = Request.Params["No"];
var DefCon5 = Request["DefCon5"];
string message = Request.Params["message"];
string redirURL = "";
if (DefCon5 == "yes")
{
Response.Write(#message);
Response.Write(#Defcon);
redirURL = "/somepage";
}
else
{
redirURL = "/DefCon5";
}
I'm noticing that the if statement fails because DefCon5 is not reading exactly as yes. I have tried with the variable from the previous page and finally a literal string "Yes". I have also tried a few different Requests with no change. I believe I may be passing Yes/No incorrectly but I'm unclearas to why this is the case.

I think you should have changes like this in your controller code
public ActionResult DefCon5(string DefCon5,string message)
{
//string yes = Request.Params["Yes"];
//string no = Request.Params["No"];
//var DefCon5 = Request["DefCon5"];
//string message = Request.Params["message"];
string redirURL = "";
if (DefCon5.ToLower() == "yes")
{
Response.Write(#message);
//Response.Write(#Defcon);
redirURL = "/somepage";
}
else
{
redirURL = "/DefCon5";
}
// your code here
return View();
}

Related

Make input fields readonly with values based on another input field

I have 3 input fields in the create user form. Based on the selection of status, I want to make the next 2 fields read-only with specific values.
So If the user selects "Full-Time" for Status, the next 2 fields should become read-only with values 5 and 7.6 respectively. For any other selection, it should remain as a normal input field for the user to enter values.
How can I achieve this? Would highly appreciate any help
You can use listener events and jquery's method attr to handle the state of the other two text boxes. Here is an example.
function changeVal(e) {
console.log(e.target.value)
if (e.target.value == "Full Time") {
$("#workingday").val(5)
$("#workinghour").val(7.6)
$("#workingday").attr("readonly", true)
$("#workinghour").attr("readonly", true)
} else {
$("#workingday").val("")
$("#workinghour").val("")
$("#workingday").attr("readonly", false)
$("#workinghour").attr("readonly", false)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<table>
<tr>
<td>status</td>
<td>Working Day in weeks</td>
<td>Working Hours Per Day</td>
</tr>
<tr>
<td>
<select onchange="changeVal(event)">
<option value="">--select--</option>
<option value="Full Time">Full Time</option>
<option value="other">other value</option>
</select>
</td>
<td>
<input type="text" id="workingday" name="workingday" value="0" />
</td>
<td>
<input type="text" id="workinghour" name="workinghour" value="0" />
</td>
</tr>
</table>
add runat attribute to Status
runat="server"
then take the value of Status and compare it to set the parameters of the other fields
String statustxt = Status.Value;
if(Equals(statustxt, targettxt) {
workingdays.Text = "5";
workingdays.ReadOnly = true;
workinghours.Text = "7.6";
workinghours.ReadOnly = true; }
You can also set Editable = false

How to increment a value within a database column by button click

As part of the project that I'm working on, users can create a post and then other users are able to click on a "like" or "dislike" button.
The code below is the Post.cs class responsible for adding the tables to the database.
public class Post
{
//The post ID
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int postId { get; set; }
// Foreign key to customer
public string Id { get; set; }
public string Email { get; set; }
public string postTitle { get; set; }
public string postBody { get; set; }
public string postDepartment { get; set; }
public string postCategory { get; set; }
public bool postAnonymous { get; set; }
public int postLikes { get; set; }
public int postDislikes { get; set; }
public DateTime postDate { get; set; }
}
The following code is the back-end C# code that's linked to either buttons.
protected void btnLike_Click(object sender, EventArgs e)
{
}
protected void btnDislike_Click(object sender, EventArgs e)
{
}
I am trying to get the buttons to increase the integer value by +1 on the database per each click and the users should only be able to click on either one without being able to like // dislike more than once.
How would I go about trying to do this successfully using the asp.net webforms.
<------------------EDIT------------------------->
protected void btnLike_Click(object sender, EventArgs e)
{
var postIDforLike = // add logic to get the id of the post to increment the likes
using (var _dbContext = new ApplicationDbContext())
{
var addLikeSql = "update post set postLikes = postLikes + 1 where postID = #id";
var paramID = new SqlParameter("#id", postIDforLike);
_dbContext.Database.ExecuteSqlCommand(addLikeSql, paramID);
}
}
<--------------------------EDIT2----------------------->
<asp:Button ID="btnLike" class="btn btn-primary" runat="server" Text="đź‘Ť Like" Width="99.99px" OnClick="btnLike_Click" />&nbsp <asp:Button ID="btnDislike" Width="99.99px" class="btn btn-primary" runat="server" Text="Dislike đź‘Ž" OnClick="btnDislike_Click" />
</div>
<br />
<%--------------------------------------
Inserting Comment Information
--------------------------------------%>
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title text-center">Add Comment</h3>
</div>
<div class="panel-body">
<fieldset>
<table class="nav-justified">
<tr>
<td class="modal-sm" style="width: 237px; height: 21px;">
<label for="commentBody" class="col-lg-2 control-label">Comment:</label></td>
<td style="width: 434px; height: 21px;">
<asp:TextBox Width="400px" style="resize:none;" class="form-control" ID="commentBody" runat="server" placeholder="Body" TextMode="MultiLine"></asp:TextBox>
</td>
<td style="height: 21px">
<asp:RequiredFieldValidator controltovalidate="commentBody" ID="commentBodyValidator" runat="server" ErrorMessage="*Comment is required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
<br />
<table class="nav-justified">
<tr>
<td style="height: 21px; width: 511px">
<label for="commentAnonymous" class="col-lg-2 control-label" style="left: 0px; top: 0px; width: 538px">Would you like this comment to be submitted anonymously?:</label></td>
<td style="height: 21px; width: 104px">
<asp:RadioButtonList ID="commentAnonymous" runat="server" BorderStyle="None" CellPadding="0" CellSpacing="0">
<asp:ListItem Value="1" Text="Yes">Yes</asp:ListItem>
<asp:ListItem Value="0" Text="No">No</asp:ListItem>
</asp:RadioButtonList>
</td>
<td style="height: 21px"><asp:RequiredFieldValidator controltovalidate="commentAnonymous" ID="commentAnonymousValidator" runat="server" ErrorMessage="*Please select an option" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
<br />
<table class="nav-justified">
<tr>
<td class="modal-sm" style="width: 408px"> </td>
<td>
<button type="reset" class="btn btn-default">Cancel</button>
<asp:Button class="btn btn-default" ID="commentSubmitBtn" runat="server" autopostback="false" onclick="AddComment" Text="Submit" />
</td>
<td> </td>
</tr>
</table>
</fieldset>
<hr>
<table class="display" id="commentsTable">
<thead>
<tr>
<th>Comment</th>
<th>User</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I assume that you use Entity Framework (based on the attributes used in the post class).
The easiest way to do that is to load the entity, increment the value and then call SaveChanges. But this is very inefficient and also dangerous, if you don't use a locking mechanism.
What you are probably looking for is a
update post set postLikes = postLikes + 1 where postID = #id
command. This would already be more efficient, because you do not load the whole post every time before updating the Likes value. You can execute Sql Commands like this using Database.ExecuteSqlCommand of your context.
Another possible solution would be to change your DB Model by adding a Like and Dislike Table where you add a record for every like/dislike. To get the current count of likes, you have to count the number of records associated to the post. This adds overhead, but has the advantage that you don't create a bottleneck because the database has to lock your post record every time you want to update the like field.
//You need to have a new table that handle user-post-like
// UserLike Table which have UserId int PostId int Like or dislike so you dont need Likes and Dislikes attributes on entity!
//Suppose that, this operation can be done by user logged in.
protected void btnLike_Click(object sender, EventArgs e)
{
//you need to get postId while button clicked...
DBContext db = new DbContext();
var user = Session["loggedUser"] as User ;
var didUserLike = db.Post.Where(p=>p.PostId == postId).Select(x=>x.UserId == user.UserId).FirstOrDefault());
if(didUserLike.Count() > 0){
//Operation like enable button disable button!
} //and if you want to do it for dislike..yes you can
}
Sorry i don't have studio or code here i cant control this.But i think you understand structure. Have a good day.
Edited(Added):
and in view you dont need to show from attribute of your enetiyt because this can be calculated with query. This is not right for database design.
and you can do it like ;
public int likeCountForPost(int id){
var postLikes = db.PostLikes.Where(x=>x.PostId == id && x.PostLike==1).Count();
return postLikes;
}
You also can do it by changing just 1 to 2 for return count of dislikes.

Put a line of string in textarea everytime I click a checkbox

Basically I want my code to update the textarea as users put a check in a checkboxes inside a table. If a checkbox is checked, a username will be placed in textarea along with line breaks. If unchecked, it will remove from textarea. After that, a button will submit every string inside the textarea.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken();
<td align="center">
<form>
<div style="max-width:50%" class="form-group #if (ViewBag.ErrorMessageDelete != null)
{ <text>has-error</text> } ">
#Html.TextArea("deleteRequest", string.Empty, 5, 100, null)
#if (ViewBag.ErrorMessageDelete != null)
{
<span class="help-block">#ViewBag.ErrorMessageDelete</span>
}
</div>
<button class="btn btn-primary" onclick="return confirm ('Removing these members, are you sure?')">Remove User(s)</button>
</form>
</td>
}
and this is my current checkbox
<td align="center" style="width:5%">
#Html.CheckBox("toBeDeleted", new { onclick = "deleteRequest = deleteRequest + item.username + <br>" });
</td>
I used textarea because I want users to be able to input usernames on their own without using checkboxes. Is it possible to do it in MVC ASP.NET in Visual Studio?
Don't do this with click event. Use change event on checkbox.
You can also try with the array. If the checkbox is checked add item to array, if not remove it. After that convert array to string, and set a value to textarea. Delete and push logic you have to implement by your own.
<td align="center" style="width:5%">
#Html.CheckBox("toBeDeleted", new { onchange="testfunc(this)", data_username = item.username });
</td>
<script>
var result = [];
function testfunc(elem) {
var username = $(elem).attr("data-username");
if($(elem).is(':checked')) {
result.push(username )
}
else{
var index = result.indexOf(username);
if (index > -1) {
result.splice(index, 1);
}
}
$("#deleteRequest").val(result.join("\n"));
}
</script>

Angular JS, multiple insert error

I want to fetch data from SQL and display in HTML table using ng-repeat option then I need to edit some values in the table cell. My problem is that I only get initial values in the controller and the changes are not reflected in the controller. Here is my code:
app.controller('CRUD_EntryController', function ($scope, CRUD_InternalEntryService) {
GetStudentMarkDetails();
function GetStudentMarkDetails() {
var PromiseGetMarks = CRUD_InternalEntryService.GetMarkDetails();
PromiseGetMarks.then(function (res) {
$scope.MarkList = res.data;
})
}
$scope.mark = {};
$scope.save = function (MarkList) {
var index = 0;
$scope.MarkList.forEach(function (mark) {
console.log('rows #' + (index++) + ': ' + JSON.stringify(mark));
alert(mark.M1);
}
}
View:
<table class=" table table-condensed" id="myresul">
<tr>
<th>Slno</th>
<th>Name</th>
<th>RegNo</th>
<th>ClassNo</th>
<th>M1</th>
<th>M2</th>
<th>M3</th>
</tr>
<tbody data-ng-repeat="mark in MarkList" >
<tr>
<td class="col-md-1" >#{{$index+1}}</td>
<td class="col-md-2" ng-model="mark.Fname">{{mark.Fname}}</td>
<td class="col-md-2">{{mark.RegNo}}</td>
<td class="col-md-1">{{mark.ClassNo}}</td>
<td class="col-md-1"><input type="number" value="{{mark.M1}}" ng-model="M1" class="form-control" /></td>
<td class="col-md-1"><input type="number" value="{{mark.M2}}" ng-model="M2" class="form-control" /></td>
<td class="col-md-1"><input type="number" value="{{mark.M3}}" ng-model="M3" class="form-control" /></td>
</tr>
<button data-ng-click="save(MarkList)" class="btn btn-success">Save</button>
</tbody>
</table>
Don't think you need to define this: $scope.mark = {}; since mark is set in the scope of your ng-repeat. Remove it because this is somewhat confusing and might cause errors in the future.
Remove the value="{{mark.M1}}" and bind your model to ng-model="{{mark.M1}}". Asuming that you wand to bind to M1, M2 and M3 in your inputs.
Also see the angular docs for ngModel for more details and update your code accordingly.
By the way you don't have to pass MarkList as an argument for Save(..), you can do this:
<button data-ng-click="save()" class="btn btn-success">Save</button>, change the Save method signature to Save() and use $scope.MarkList instead of the argument MarkList.
Or change your method to only save the specific mark instead of the entire list every time.

Check html field hidden or not using C# backend code

I have the following code in which I am showing and hiding html controls based on Dropdown list selected value. Show and Hide is working fine but I want to Check in backend i.e C# that the which <tr> is visible and which one is hidden.
Here is my aspx page code
<script type="text/javascript">
$(document).ready(function () {
$("#AttachemntType").change(function () {
if ($(this).val() == "F") {
$("#tr_CompileFile").show();
$("#tr_SourceFile").show();
}
else if ($(this).val() == "R") {
$("#tr_CompileFile").hide();
$("#tr_SourceFile").show();
}
else {
$("#tr_SourceFile").hide();
$("#tr_CompileFile").hide();
}
});
});
</script>
<tr bgcolor="white">
<td style="height: 20px">
Attachment Type
</td>
<td>
<select id="AttachemntType" name="AttachemntType" style="width: 344px">
<option value="0">Select</option>
<option value="F">Form</option>
<option value="R">Report</option>
</select>
</td>
</tr>
<tr bgcolor="white" id="tr_SourceFile" style="display:none;" runat="server">
<td style="height: 20px">
Source File
</td>
<td>
<input class="body_text" type="file" id="src_File" name="src_File" runat="server"
style="width: 420px" />
</td>
</tr>
<tr bgcolor="white" id="tr_CompileFile" style="display:none;" runat="server">
<td style="height: 20px">
Compiled File
</td>
<td style="height: 16px; width: 625px;">
<input class="body_text" type="file" id="comp_File" runat="server" style="width: 420px" />
</td>
</tr>
This is the code which I am trying in Backend but its returning always true for all fields
if (tr_CompileFile.Visible == true && tr_SourceFile.Visible == true)
{
//This Condition is always true
}
else if (tr_SourceFile.Visible == true && tr_CompileFile.Visible == false)
{
//something
}
else
{
//something else
}
You cannot actually check this in backend. .show() and .hide() are jQuery methods which only operates on client side.
One workaround could be to use a MVVM pattern with knockout.js (Don’t try angular for that, you’ll be lost in docs)
Another option is to actually put your select box and the hidden/visible parts into UpdatePanel. So when you change the selector, the server side is called and you can assign / remove “visible” field.
More : https://msdn.microsoft.com/en-us/library/bb399001.aspx
In last resort, you can put a hidden field, which will be populated on submit with “hidden,shown,etc” values for you inputs.
Personally, I’ll vote for the first, but second is the easiest one to implement
Yes, Jurion was right. just adding more explanation: you can try
tr_CompileFile.Style["HTML Style key here"]
for example you can try
tr_CompileFile.Style["display"]
but it will return to you the value of the particular style defined in your aspx files, not the actual style displayed and changed in client side.
If you defined
<asp:Button ID="btnTest" runat="server" style="display:none" />
when you check it,
btnTest.Style["display"]
will return "none"

Categories