Adding to a list removes from another listA potentially dangerous Request.Form value was detected from the clientHow do you create a dropdownlist from an enum in ASP.NET MVC?How do I update the GUI from another thread?Using LINQ to remove elements from a List<T>Get int value from enum in C#Call one constructor from anotherValidation of a Dropdown which property comes from model but created from a RenderActionWhy not inherit from List<T>?ASP Core MVC Scaffolding SelectList (RC1) not populating dataSet the rendered value to the dropdown using ajax jquery

Is an easily guessed plot twist a good plot twist?

How to sort and filter a constantly changing list of data?

What is "ass door"?

What do teaching faculty do during semester breaks?

Why is a dedicated QA team member necessary?

Memory capability and powers of 2

Is there a published campaign where a missing artifact or a relic is creating trouble by its absence?

Is the 2-Category of groupoids locally presentable?

Is the apartment I want to rent a scam?

Should I describe a character deeply before killing it?

How do I run a game when my PCs have different approaches to combat?

Are gangsters hired to attack people at a train station classified as a terrorist attack?

Does static fire reduce reliability?

Where is this photo of a group of hikers taken? Is it really in the Ural?

Film where a boy turns into a princess

Character Frequency in a String

Why does more variables mean deeper trees in random forest?

What is a reasonable time for modern human society to adapt to dungeons?

401(k) investment after being fired. Do I own it?

Sitecore Powershell extensions module compatibility with Sitecore 9.2

What do I do when a student working in my lab "ghosts" me?

How can I tell if there was a power cut while I was out?

This message is flooding my syslog, how to find were it comes from?

How can I create a shape in Illustrator which follows a path in descending order size?



Adding to a list removes from another list


A potentially dangerous Request.Form value was detected from the clientHow do you create a dropdownlist from an enum in ASP.NET MVC?How do I update the GUI from another thread?Using LINQ to remove elements from a List<T>Get int value from enum in C#Call one constructor from anotherValidation of a Dropdown which property comes from model but created from a RenderActionWhy not inherit from List<T>?ASP Core MVC Scaffolding SelectList (RC1) not populating dataSet the rendered value to the dropdown using ajax jquery






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am very new to coding and asp.net.
I am creating a web application as part of course work. The application allows users to create causes and sign other causes. The problem I am having is that when a user signs a second cause their name is removed from the first cause. I hope this makes sense and I would appreciate any help



This is the model for my cause. The Cause has a list that will hold the users and is displayed to other users.



[Key]
public int CauseId get; set;
[Required(ErrorMessage = "A Title is required")]
[StringLength(160)]
public string Title get; set;
public int UserId get; set;
[DisplayName("Category")]
[Required(ErrorMessage = "A Category is required")]
public string Genre get; set;
[DisplayName("Created by")]
public string CreatedBy get; set;
[ScaffoldColumn(false)]
[DisplayFormat(DataFormatString = "0:dd MMM yyyy", ApplyFormatInEditMode = true)]
[DisplayName("Created on")]
public DateTime CreatedTime get; set;
[Required(ErrorMessage = "A Description is required")]
[StringLength(10000, MinimumLength = 1)]
[DisplayName("Description")]
public string Description get; set;
[Required(ErrorMessage = "A Target is required")]
[Range(10, 1000, ErrorMessage = "Target Signatures must be between 10 and 1000")]
public int Target get; set;
public virtual ICollection<SiteUser> Signatures get; set;
[DisplayName("No. of Signatures")]
public int SignatureCount get; set;
[DisplayName("Cause Image")]
[StringLength(1024)]
public string CauseImageUrl get; set;
public string Image get; set;


This is the model for my user



public int ID get; set; 
public string Username get; set;
public string Email get; set;
public string Password get; set;
[DisplayName("User Image")]
public string UserImageUrl get; set;


This is the method I am using for the user to sign the cause



public JsonResult Sign(int? id)
{
var result = "Fail";
if(id == null)

Response.StatusCode = 400;
result = "Bad Request, check input";
return Json(result, JsonRequestBehavior.AllowGet);

if (Session["UserID"] == null)

Response.StatusCode = 403;
result = "Access forbidden";
return Json(result, JsonRequestBehavior.AllowGet);


Cause cause = db.Causes.Find(id);
int memberID = Convert.ToInt32(Session["UserID"].ToString());
SiteUser user = db.SiteUsers.Find(memberID);

cause.Signatures.Add(user);

db.SaveChanges();
Response.StatusCode = 200;
result = "Thanks for signing this cause";
return Json(result, JsonRequestBehavior.AllowGet);


Code the details view



 @model Coursework.Models.Cause

@ ViewBag.Title = "Details";
<div class="bg"></div>
<div class="jumbotron" style="height:200px; background-image: url(@Model.CauseImageUrl);">
<h2 class="text-light bg-dark display-1">@Model.Title</h2>
</div>


<div class="container my-5">

<div class="row ">
<div class="col-md-6">
<div class="row">
<div class="col-4">
<h5>Category:</h5>
@Html.DisplayFor(model => model.Genre)
</div>
<div class="col-4">
<h5>
@Html.DisplayNameFor(model => model.CreatedBy):
</h5>
@Html.DisplayFor(model => model.CreatedBy)
</div>
<div class="col-4">
<h5>
@Html.DisplayNameFor(model => model.CreatedTime):
</h5>
@Html.DisplayFor(model => model.CreatedTime)
</div>
</div>
<hr />
<div class="row">
</div>
<h5>Description:</h5>
<p>@Html.DisplayFor(model => model.Description)</p>
</div>

<div class="container col-md-6">
<h5>
Target number of signatures: @Html.DisplayFor(model => model.Target)
</h5>
<div class="progress my-2">
<div class="progress-bar progress-bar-striped progress-bar-animated" id="progressBar" role="progressbar" aria-valuenow="7" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="row">
<div class="col-12">
@
Html.RenderPartial("_Sign", Model);

<div class='signMessage' id='addSignBtn'>Click here to sign</div>
<div id="socialMedia">
<a href="#" class="fab fa-facebook fa-3x"></a>
<a href="#" class="fab fa-twitter fa-3x"></a>
<a href="#" class="fab fa-linkedin fa-3x"></a>
</div>

</div>
</div>
</div>
</div>
</div>
<script>

//Add edit button
$('#addEditBtn').append(' @Html.ActionLink("Edit", "Edit", new id = Model.CauseId , new @class = "btn btn-outline-secondary" )');
$('#addLoginBtn').append('<button type="button" class="btn btn-success mr-2 my-2" data-toggle="modal" data-target="#myModal" style="cursor:pointer" id="loginBtn">Sign</button>');
$('#addSignBtn').append('<button type="button" class="btn btn-success ml-2" style="cursor:pointer" id="signbtn">Sign</button>');
//update progress bar
var progressBar = $('#progressBar');
var progressIncrease = 1/@Model.Target * 100;
var progressWidth = @Model.SignatureCount * progressIncrease;
progressBar.width(progressWidth + "%");


var signaturesTable = $('#signatures');
var $signbtn = $('#signbtn');

//hide thanks message
$('#signSuccess').hide();


//hide sign button if user created this and show edit

$signbtn.on('click', function (event)
event.preventDefault();
var data = @Model.CauseId.ToString();

$.ajax(
type: "post",
data: data,
url: "/Causes/Sign/@Model.CauseId",
success: function (result)
if (result = "Thanks for signing this cause")
$('#signSuccessText').text(result);
progressBar.width(progressWidth + progressIncrease + "%");
$('#signatures').append('<tr><td><img src="@Session["UserImage"]" width="50px"</td><td>@Session["Username"]</td></tr>');
$('#signbtn').fadeOut(500);
$('#addSignBtn').fadeOut(500);
$('#signSuccess').fadeIn(500);
$('#noSigns').hide();
$('#signCount').text(@Model.SignatureCount + 1);




);
);
</script>


And the partial view



@model Coursework.Models.Cause
<h5>Signatures: <span class="badge badge-success" id="signCount">@Model.SignatureCount</span></h5>
<table id="signatures" class="col-sm-12 table table-striped">
<th>
User Image
</th>
<th>
Name
</th>
@foreach (var x in Model.Signatures)

<tr>
<td>
<img style="width:50px" src="@x.UserImageUrl" alt="user image" />
</td>
<td>@x.Username</td>
</tr>

</table>
@if (Model.Signatures.Count < 1)

<div id="noSigns">
<h6>No signatures yet, be the first</h6>
</div>

<div>
@Html.Raw(ViewBag.signed)
</div>
<div id="signSuccess" class="alert alert-success alert-dismissible">
<a id="linkClose" class="close" href="#" data-dismiss="alert">&times;</a>
<div id="signSuccessText">Thanks for signing!</div>
</div>









share|improve this question



















  • 1





    the code here only adds a user to a cause. I don't see any code which would remove them. Are you actually seeing records disappearing from the database? That sounds unlikely, based on this. Or do you maybe just have an issue somewhere else in the code? Perhaps you have a view which is meant to display all the causes a user signed up for, but which has a bug and only displays the most recent one? I'm speculating, but that sounds far more likely than a problem with the code you've shown us.

    – ADyson
    Mar 26 at 16:10











  • When I view the SQL Server Object explorer the Signatures list is not there, so cant see if the data is in the database.

    – seanrobmaguire
    Mar 26 at 16:45











  • You're using SSMS to view it, I assume? The only cases I can think of for that are either somehow your user account doesn't have permission to the table, or you added it recently and haven't refreshed your object list, or you're looking in the wrong copy of the database

    – ADyson
    Mar 26 at 17:11











  • Of course you could just open a new query window in your database and write a SELECT statement manually to get the contents of the table. You're not obliged to use the GUI

    – ADyson
    Mar 26 at 17:12











  • Thanks, I have tired that and it looks like a column has been added to the SiteUsers table called Cause_CauseId and that is updated when the sign button is pressed. Any ideas why this is happening? ID Username Email Password UserImageUrl Cause_CauseId 1 Username1 user1@email.com Password1 /Images/generic-user-icon-19.jpg NULL 2 Username2 user2@email.com Password1 /Images/generic-user-icon-19.jpg 1

    – seanrobmaguire
    Mar 26 at 17:46

















0















I am very new to coding and asp.net.
I am creating a web application as part of course work. The application allows users to create causes and sign other causes. The problem I am having is that when a user signs a second cause their name is removed from the first cause. I hope this makes sense and I would appreciate any help



This is the model for my cause. The Cause has a list that will hold the users and is displayed to other users.



[Key]
public int CauseId get; set;
[Required(ErrorMessage = "A Title is required")]
[StringLength(160)]
public string Title get; set;
public int UserId get; set;
[DisplayName("Category")]
[Required(ErrorMessage = "A Category is required")]
public string Genre get; set;
[DisplayName("Created by")]
public string CreatedBy get; set;
[ScaffoldColumn(false)]
[DisplayFormat(DataFormatString = "0:dd MMM yyyy", ApplyFormatInEditMode = true)]
[DisplayName("Created on")]
public DateTime CreatedTime get; set;
[Required(ErrorMessage = "A Description is required")]
[StringLength(10000, MinimumLength = 1)]
[DisplayName("Description")]
public string Description get; set;
[Required(ErrorMessage = "A Target is required")]
[Range(10, 1000, ErrorMessage = "Target Signatures must be between 10 and 1000")]
public int Target get; set;
public virtual ICollection<SiteUser> Signatures get; set;
[DisplayName("No. of Signatures")]
public int SignatureCount get; set;
[DisplayName("Cause Image")]
[StringLength(1024)]
public string CauseImageUrl get; set;
public string Image get; set;


This is the model for my user



public int ID get; set; 
public string Username get; set;
public string Email get; set;
public string Password get; set;
[DisplayName("User Image")]
public string UserImageUrl get; set;


This is the method I am using for the user to sign the cause



public JsonResult Sign(int? id)
{
var result = "Fail";
if(id == null)

Response.StatusCode = 400;
result = "Bad Request, check input";
return Json(result, JsonRequestBehavior.AllowGet);

if (Session["UserID"] == null)

Response.StatusCode = 403;
result = "Access forbidden";
return Json(result, JsonRequestBehavior.AllowGet);


Cause cause = db.Causes.Find(id);
int memberID = Convert.ToInt32(Session["UserID"].ToString());
SiteUser user = db.SiteUsers.Find(memberID);

cause.Signatures.Add(user);

db.SaveChanges();
Response.StatusCode = 200;
result = "Thanks for signing this cause";
return Json(result, JsonRequestBehavior.AllowGet);


Code the details view



 @model Coursework.Models.Cause

@ ViewBag.Title = "Details";
<div class="bg"></div>
<div class="jumbotron" style="height:200px; background-image: url(@Model.CauseImageUrl);">
<h2 class="text-light bg-dark display-1">@Model.Title</h2>
</div>


<div class="container my-5">

<div class="row ">
<div class="col-md-6">
<div class="row">
<div class="col-4">
<h5>Category:</h5>
@Html.DisplayFor(model => model.Genre)
</div>
<div class="col-4">
<h5>
@Html.DisplayNameFor(model => model.CreatedBy):
</h5>
@Html.DisplayFor(model => model.CreatedBy)
</div>
<div class="col-4">
<h5>
@Html.DisplayNameFor(model => model.CreatedTime):
</h5>
@Html.DisplayFor(model => model.CreatedTime)
</div>
</div>
<hr />
<div class="row">
</div>
<h5>Description:</h5>
<p>@Html.DisplayFor(model => model.Description)</p>
</div>

<div class="container col-md-6">
<h5>
Target number of signatures: @Html.DisplayFor(model => model.Target)
</h5>
<div class="progress my-2">
<div class="progress-bar progress-bar-striped progress-bar-animated" id="progressBar" role="progressbar" aria-valuenow="7" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="row">
<div class="col-12">
@
Html.RenderPartial("_Sign", Model);

<div class='signMessage' id='addSignBtn'>Click here to sign</div>
<div id="socialMedia">
<a href="#" class="fab fa-facebook fa-3x"></a>
<a href="#" class="fab fa-twitter fa-3x"></a>
<a href="#" class="fab fa-linkedin fa-3x"></a>
</div>

</div>
</div>
</div>
</div>
</div>
<script>

//Add edit button
$('#addEditBtn').append(' @Html.ActionLink("Edit", "Edit", new id = Model.CauseId , new @class = "btn btn-outline-secondary" )');
$('#addLoginBtn').append('<button type="button" class="btn btn-success mr-2 my-2" data-toggle="modal" data-target="#myModal" style="cursor:pointer" id="loginBtn">Sign</button>');
$('#addSignBtn').append('<button type="button" class="btn btn-success ml-2" style="cursor:pointer" id="signbtn">Sign</button>');
//update progress bar
var progressBar = $('#progressBar');
var progressIncrease = 1/@Model.Target * 100;
var progressWidth = @Model.SignatureCount * progressIncrease;
progressBar.width(progressWidth + "%");


var signaturesTable = $('#signatures');
var $signbtn = $('#signbtn');

//hide thanks message
$('#signSuccess').hide();


//hide sign button if user created this and show edit

$signbtn.on('click', function (event)
event.preventDefault();
var data = @Model.CauseId.ToString();

$.ajax(
type: "post",
data: data,
url: "/Causes/Sign/@Model.CauseId",
success: function (result)
if (result = "Thanks for signing this cause")
$('#signSuccessText').text(result);
progressBar.width(progressWidth + progressIncrease + "%");
$('#signatures').append('<tr><td><img src="@Session["UserImage"]" width="50px"</td><td>@Session["Username"]</td></tr>');
$('#signbtn').fadeOut(500);
$('#addSignBtn').fadeOut(500);
$('#signSuccess').fadeIn(500);
$('#noSigns').hide();
$('#signCount').text(@Model.SignatureCount + 1);




);
);
</script>


And the partial view



@model Coursework.Models.Cause
<h5>Signatures: <span class="badge badge-success" id="signCount">@Model.SignatureCount</span></h5>
<table id="signatures" class="col-sm-12 table table-striped">
<th>
User Image
</th>
<th>
Name
</th>
@foreach (var x in Model.Signatures)

<tr>
<td>
<img style="width:50px" src="@x.UserImageUrl" alt="user image" />
</td>
<td>@x.Username</td>
</tr>

</table>
@if (Model.Signatures.Count < 1)

<div id="noSigns">
<h6>No signatures yet, be the first</h6>
</div>

<div>
@Html.Raw(ViewBag.signed)
</div>
<div id="signSuccess" class="alert alert-success alert-dismissible">
<a id="linkClose" class="close" href="#" data-dismiss="alert">&times;</a>
<div id="signSuccessText">Thanks for signing!</div>
</div>









share|improve this question



















  • 1





    the code here only adds a user to a cause. I don't see any code which would remove them. Are you actually seeing records disappearing from the database? That sounds unlikely, based on this. Or do you maybe just have an issue somewhere else in the code? Perhaps you have a view which is meant to display all the causes a user signed up for, but which has a bug and only displays the most recent one? I'm speculating, but that sounds far more likely than a problem with the code you've shown us.

    – ADyson
    Mar 26 at 16:10











  • When I view the SQL Server Object explorer the Signatures list is not there, so cant see if the data is in the database.

    – seanrobmaguire
    Mar 26 at 16:45











  • You're using SSMS to view it, I assume? The only cases I can think of for that are either somehow your user account doesn't have permission to the table, or you added it recently and haven't refreshed your object list, or you're looking in the wrong copy of the database

    – ADyson
    Mar 26 at 17:11











  • Of course you could just open a new query window in your database and write a SELECT statement manually to get the contents of the table. You're not obliged to use the GUI

    – ADyson
    Mar 26 at 17:12











  • Thanks, I have tired that and it looks like a column has been added to the SiteUsers table called Cause_CauseId and that is updated when the sign button is pressed. Any ideas why this is happening? ID Username Email Password UserImageUrl Cause_CauseId 1 Username1 user1@email.com Password1 /Images/generic-user-icon-19.jpg NULL 2 Username2 user2@email.com Password1 /Images/generic-user-icon-19.jpg 1

    – seanrobmaguire
    Mar 26 at 17:46













0












0








0








I am very new to coding and asp.net.
I am creating a web application as part of course work. The application allows users to create causes and sign other causes. The problem I am having is that when a user signs a second cause their name is removed from the first cause. I hope this makes sense and I would appreciate any help



This is the model for my cause. The Cause has a list that will hold the users and is displayed to other users.



[Key]
public int CauseId get; set;
[Required(ErrorMessage = "A Title is required")]
[StringLength(160)]
public string Title get; set;
public int UserId get; set;
[DisplayName("Category")]
[Required(ErrorMessage = "A Category is required")]
public string Genre get; set;
[DisplayName("Created by")]
public string CreatedBy get; set;
[ScaffoldColumn(false)]
[DisplayFormat(DataFormatString = "0:dd MMM yyyy", ApplyFormatInEditMode = true)]
[DisplayName("Created on")]
public DateTime CreatedTime get; set;
[Required(ErrorMessage = "A Description is required")]
[StringLength(10000, MinimumLength = 1)]
[DisplayName("Description")]
public string Description get; set;
[Required(ErrorMessage = "A Target is required")]
[Range(10, 1000, ErrorMessage = "Target Signatures must be between 10 and 1000")]
public int Target get; set;
public virtual ICollection<SiteUser> Signatures get; set;
[DisplayName("No. of Signatures")]
public int SignatureCount get; set;
[DisplayName("Cause Image")]
[StringLength(1024)]
public string CauseImageUrl get; set;
public string Image get; set;


This is the model for my user



public int ID get; set; 
public string Username get; set;
public string Email get; set;
public string Password get; set;
[DisplayName("User Image")]
public string UserImageUrl get; set;


This is the method I am using for the user to sign the cause



public JsonResult Sign(int? id)
{
var result = "Fail";
if(id == null)

Response.StatusCode = 400;
result = "Bad Request, check input";
return Json(result, JsonRequestBehavior.AllowGet);

if (Session["UserID"] == null)

Response.StatusCode = 403;
result = "Access forbidden";
return Json(result, JsonRequestBehavior.AllowGet);


Cause cause = db.Causes.Find(id);
int memberID = Convert.ToInt32(Session["UserID"].ToString());
SiteUser user = db.SiteUsers.Find(memberID);

cause.Signatures.Add(user);

db.SaveChanges();
Response.StatusCode = 200;
result = "Thanks for signing this cause";
return Json(result, JsonRequestBehavior.AllowGet);


Code the details view



 @model Coursework.Models.Cause

@ ViewBag.Title = "Details";
<div class="bg"></div>
<div class="jumbotron" style="height:200px; background-image: url(@Model.CauseImageUrl);">
<h2 class="text-light bg-dark display-1">@Model.Title</h2>
</div>


<div class="container my-5">

<div class="row ">
<div class="col-md-6">
<div class="row">
<div class="col-4">
<h5>Category:</h5>
@Html.DisplayFor(model => model.Genre)
</div>
<div class="col-4">
<h5>
@Html.DisplayNameFor(model => model.CreatedBy):
</h5>
@Html.DisplayFor(model => model.CreatedBy)
</div>
<div class="col-4">
<h5>
@Html.DisplayNameFor(model => model.CreatedTime):
</h5>
@Html.DisplayFor(model => model.CreatedTime)
</div>
</div>
<hr />
<div class="row">
</div>
<h5>Description:</h5>
<p>@Html.DisplayFor(model => model.Description)</p>
</div>

<div class="container col-md-6">
<h5>
Target number of signatures: @Html.DisplayFor(model => model.Target)
</h5>
<div class="progress my-2">
<div class="progress-bar progress-bar-striped progress-bar-animated" id="progressBar" role="progressbar" aria-valuenow="7" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="row">
<div class="col-12">
@
Html.RenderPartial("_Sign", Model);

<div class='signMessage' id='addSignBtn'>Click here to sign</div>
<div id="socialMedia">
<a href="#" class="fab fa-facebook fa-3x"></a>
<a href="#" class="fab fa-twitter fa-3x"></a>
<a href="#" class="fab fa-linkedin fa-3x"></a>
</div>

</div>
</div>
</div>
</div>
</div>
<script>

//Add edit button
$('#addEditBtn').append(' @Html.ActionLink("Edit", "Edit", new id = Model.CauseId , new @class = "btn btn-outline-secondary" )');
$('#addLoginBtn').append('<button type="button" class="btn btn-success mr-2 my-2" data-toggle="modal" data-target="#myModal" style="cursor:pointer" id="loginBtn">Sign</button>');
$('#addSignBtn').append('<button type="button" class="btn btn-success ml-2" style="cursor:pointer" id="signbtn">Sign</button>');
//update progress bar
var progressBar = $('#progressBar');
var progressIncrease = 1/@Model.Target * 100;
var progressWidth = @Model.SignatureCount * progressIncrease;
progressBar.width(progressWidth + "%");


var signaturesTable = $('#signatures');
var $signbtn = $('#signbtn');

//hide thanks message
$('#signSuccess').hide();


//hide sign button if user created this and show edit

$signbtn.on('click', function (event)
event.preventDefault();
var data = @Model.CauseId.ToString();

$.ajax(
type: "post",
data: data,
url: "/Causes/Sign/@Model.CauseId",
success: function (result)
if (result = "Thanks for signing this cause")
$('#signSuccessText').text(result);
progressBar.width(progressWidth + progressIncrease + "%");
$('#signatures').append('<tr><td><img src="@Session["UserImage"]" width="50px"</td><td>@Session["Username"]</td></tr>');
$('#signbtn').fadeOut(500);
$('#addSignBtn').fadeOut(500);
$('#signSuccess').fadeIn(500);
$('#noSigns').hide();
$('#signCount').text(@Model.SignatureCount + 1);




);
);
</script>


And the partial view



@model Coursework.Models.Cause
<h5>Signatures: <span class="badge badge-success" id="signCount">@Model.SignatureCount</span></h5>
<table id="signatures" class="col-sm-12 table table-striped">
<th>
User Image
</th>
<th>
Name
</th>
@foreach (var x in Model.Signatures)

<tr>
<td>
<img style="width:50px" src="@x.UserImageUrl" alt="user image" />
</td>
<td>@x.Username</td>
</tr>

</table>
@if (Model.Signatures.Count < 1)

<div id="noSigns">
<h6>No signatures yet, be the first</h6>
</div>

<div>
@Html.Raw(ViewBag.signed)
</div>
<div id="signSuccess" class="alert alert-success alert-dismissible">
<a id="linkClose" class="close" href="#" data-dismiss="alert">&times;</a>
<div id="signSuccessText">Thanks for signing!</div>
</div>









share|improve this question
















I am very new to coding and asp.net.
I am creating a web application as part of course work. The application allows users to create causes and sign other causes. The problem I am having is that when a user signs a second cause their name is removed from the first cause. I hope this makes sense and I would appreciate any help



This is the model for my cause. The Cause has a list that will hold the users and is displayed to other users.



[Key]
public int CauseId get; set;
[Required(ErrorMessage = "A Title is required")]
[StringLength(160)]
public string Title get; set;
public int UserId get; set;
[DisplayName("Category")]
[Required(ErrorMessage = "A Category is required")]
public string Genre get; set;
[DisplayName("Created by")]
public string CreatedBy get; set;
[ScaffoldColumn(false)]
[DisplayFormat(DataFormatString = "0:dd MMM yyyy", ApplyFormatInEditMode = true)]
[DisplayName("Created on")]
public DateTime CreatedTime get; set;
[Required(ErrorMessage = "A Description is required")]
[StringLength(10000, MinimumLength = 1)]
[DisplayName("Description")]
public string Description get; set;
[Required(ErrorMessage = "A Target is required")]
[Range(10, 1000, ErrorMessage = "Target Signatures must be between 10 and 1000")]
public int Target get; set;
public virtual ICollection<SiteUser> Signatures get; set;
[DisplayName("No. of Signatures")]
public int SignatureCount get; set;
[DisplayName("Cause Image")]
[StringLength(1024)]
public string CauseImageUrl get; set;
public string Image get; set;


This is the model for my user



public int ID get; set; 
public string Username get; set;
public string Email get; set;
public string Password get; set;
[DisplayName("User Image")]
public string UserImageUrl get; set;


This is the method I am using for the user to sign the cause



public JsonResult Sign(int? id)
{
var result = "Fail";
if(id == null)

Response.StatusCode = 400;
result = "Bad Request, check input";
return Json(result, JsonRequestBehavior.AllowGet);

if (Session["UserID"] == null)

Response.StatusCode = 403;
result = "Access forbidden";
return Json(result, JsonRequestBehavior.AllowGet);


Cause cause = db.Causes.Find(id);
int memberID = Convert.ToInt32(Session["UserID"].ToString());
SiteUser user = db.SiteUsers.Find(memberID);

cause.Signatures.Add(user);

db.SaveChanges();
Response.StatusCode = 200;
result = "Thanks for signing this cause";
return Json(result, JsonRequestBehavior.AllowGet);


Code the details view



 @model Coursework.Models.Cause

@ ViewBag.Title = "Details";
<div class="bg"></div>
<div class="jumbotron" style="height:200px; background-image: url(@Model.CauseImageUrl);">
<h2 class="text-light bg-dark display-1">@Model.Title</h2>
</div>


<div class="container my-5">

<div class="row ">
<div class="col-md-6">
<div class="row">
<div class="col-4">
<h5>Category:</h5>
@Html.DisplayFor(model => model.Genre)
</div>
<div class="col-4">
<h5>
@Html.DisplayNameFor(model => model.CreatedBy):
</h5>
@Html.DisplayFor(model => model.CreatedBy)
</div>
<div class="col-4">
<h5>
@Html.DisplayNameFor(model => model.CreatedTime):
</h5>
@Html.DisplayFor(model => model.CreatedTime)
</div>
</div>
<hr />
<div class="row">
</div>
<h5>Description:</h5>
<p>@Html.DisplayFor(model => model.Description)</p>
</div>

<div class="container col-md-6">
<h5>
Target number of signatures: @Html.DisplayFor(model => model.Target)
</h5>
<div class="progress my-2">
<div class="progress-bar progress-bar-striped progress-bar-animated" id="progressBar" role="progressbar" aria-valuenow="7" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="row">
<div class="col-12">
@
Html.RenderPartial("_Sign", Model);

<div class='signMessage' id='addSignBtn'>Click here to sign</div>
<div id="socialMedia">
<a href="#" class="fab fa-facebook fa-3x"></a>
<a href="#" class="fab fa-twitter fa-3x"></a>
<a href="#" class="fab fa-linkedin fa-3x"></a>
</div>

</div>
</div>
</div>
</div>
</div>
<script>

//Add edit button
$('#addEditBtn').append(' @Html.ActionLink("Edit", "Edit", new id = Model.CauseId , new @class = "btn btn-outline-secondary" )');
$('#addLoginBtn').append('<button type="button" class="btn btn-success mr-2 my-2" data-toggle="modal" data-target="#myModal" style="cursor:pointer" id="loginBtn">Sign</button>');
$('#addSignBtn').append('<button type="button" class="btn btn-success ml-2" style="cursor:pointer" id="signbtn">Sign</button>');
//update progress bar
var progressBar = $('#progressBar');
var progressIncrease = 1/@Model.Target * 100;
var progressWidth = @Model.SignatureCount * progressIncrease;
progressBar.width(progressWidth + "%");


var signaturesTable = $('#signatures');
var $signbtn = $('#signbtn');

//hide thanks message
$('#signSuccess').hide();


//hide sign button if user created this and show edit

$signbtn.on('click', function (event)
event.preventDefault();
var data = @Model.CauseId.ToString();

$.ajax(
type: "post",
data: data,
url: "/Causes/Sign/@Model.CauseId",
success: function (result)
if (result = "Thanks for signing this cause")
$('#signSuccessText').text(result);
progressBar.width(progressWidth + progressIncrease + "%");
$('#signatures').append('<tr><td><img src="@Session["UserImage"]" width="50px"</td><td>@Session["Username"]</td></tr>');
$('#signbtn').fadeOut(500);
$('#addSignBtn').fadeOut(500);
$('#signSuccess').fadeIn(500);
$('#noSigns').hide();
$('#signCount').text(@Model.SignatureCount + 1);




);
);
</script>


And the partial view



@model Coursework.Models.Cause
<h5>Signatures: <span class="badge badge-success" id="signCount">@Model.SignatureCount</span></h5>
<table id="signatures" class="col-sm-12 table table-striped">
<th>
User Image
</th>
<th>
Name
</th>
@foreach (var x in Model.Signatures)

<tr>
<td>
<img style="width:50px" src="@x.UserImageUrl" alt="user image" />
</td>
<td>@x.Username</td>
</tr>

</table>
@if (Model.Signatures.Count < 1)

<div id="noSigns">
<h6>No signatures yet, be the first</h6>
</div>

<div>
@Html.Raw(ViewBag.signed)
</div>
<div id="signSuccess" class="alert alert-success alert-dismissible">
<a id="linkClose" class="close" href="#" data-dismiss="alert">&times;</a>
<div id="signSuccessText">Thanks for signing!</div>
</div>






c# asp.net asp.net-mvc entity-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 16:50







seanrobmaguire

















asked Mar 26 at 15:49









seanrobmaguireseanrobmaguire

11 bronze badge




11 bronze badge







  • 1





    the code here only adds a user to a cause. I don't see any code which would remove them. Are you actually seeing records disappearing from the database? That sounds unlikely, based on this. Or do you maybe just have an issue somewhere else in the code? Perhaps you have a view which is meant to display all the causes a user signed up for, but which has a bug and only displays the most recent one? I'm speculating, but that sounds far more likely than a problem with the code you've shown us.

    – ADyson
    Mar 26 at 16:10











  • When I view the SQL Server Object explorer the Signatures list is not there, so cant see if the data is in the database.

    – seanrobmaguire
    Mar 26 at 16:45











  • You're using SSMS to view it, I assume? The only cases I can think of for that are either somehow your user account doesn't have permission to the table, or you added it recently and haven't refreshed your object list, or you're looking in the wrong copy of the database

    – ADyson
    Mar 26 at 17:11











  • Of course you could just open a new query window in your database and write a SELECT statement manually to get the contents of the table. You're not obliged to use the GUI

    – ADyson
    Mar 26 at 17:12











  • Thanks, I have tired that and it looks like a column has been added to the SiteUsers table called Cause_CauseId and that is updated when the sign button is pressed. Any ideas why this is happening? ID Username Email Password UserImageUrl Cause_CauseId 1 Username1 user1@email.com Password1 /Images/generic-user-icon-19.jpg NULL 2 Username2 user2@email.com Password1 /Images/generic-user-icon-19.jpg 1

    – seanrobmaguire
    Mar 26 at 17:46












  • 1





    the code here only adds a user to a cause. I don't see any code which would remove them. Are you actually seeing records disappearing from the database? That sounds unlikely, based on this. Or do you maybe just have an issue somewhere else in the code? Perhaps you have a view which is meant to display all the causes a user signed up for, but which has a bug and only displays the most recent one? I'm speculating, but that sounds far more likely than a problem with the code you've shown us.

    – ADyson
    Mar 26 at 16:10











  • When I view the SQL Server Object explorer the Signatures list is not there, so cant see if the data is in the database.

    – seanrobmaguire
    Mar 26 at 16:45











  • You're using SSMS to view it, I assume? The only cases I can think of for that are either somehow your user account doesn't have permission to the table, or you added it recently and haven't refreshed your object list, or you're looking in the wrong copy of the database

    – ADyson
    Mar 26 at 17:11











  • Of course you could just open a new query window in your database and write a SELECT statement manually to get the contents of the table. You're not obliged to use the GUI

    – ADyson
    Mar 26 at 17:12











  • Thanks, I have tired that and it looks like a column has been added to the SiteUsers table called Cause_CauseId and that is updated when the sign button is pressed. Any ideas why this is happening? ID Username Email Password UserImageUrl Cause_CauseId 1 Username1 user1@email.com Password1 /Images/generic-user-icon-19.jpg NULL 2 Username2 user2@email.com Password1 /Images/generic-user-icon-19.jpg 1

    – seanrobmaguire
    Mar 26 at 17:46







1




1





the code here only adds a user to a cause. I don't see any code which would remove them. Are you actually seeing records disappearing from the database? That sounds unlikely, based on this. Or do you maybe just have an issue somewhere else in the code? Perhaps you have a view which is meant to display all the causes a user signed up for, but which has a bug and only displays the most recent one? I'm speculating, but that sounds far more likely than a problem with the code you've shown us.

– ADyson
Mar 26 at 16:10





the code here only adds a user to a cause. I don't see any code which would remove them. Are you actually seeing records disappearing from the database? That sounds unlikely, based on this. Or do you maybe just have an issue somewhere else in the code? Perhaps you have a view which is meant to display all the causes a user signed up for, but which has a bug and only displays the most recent one? I'm speculating, but that sounds far more likely than a problem with the code you've shown us.

– ADyson
Mar 26 at 16:10













When I view the SQL Server Object explorer the Signatures list is not there, so cant see if the data is in the database.

– seanrobmaguire
Mar 26 at 16:45





When I view the SQL Server Object explorer the Signatures list is not there, so cant see if the data is in the database.

– seanrobmaguire
Mar 26 at 16:45













You're using SSMS to view it, I assume? The only cases I can think of for that are either somehow your user account doesn't have permission to the table, or you added it recently and haven't refreshed your object list, or you're looking in the wrong copy of the database

– ADyson
Mar 26 at 17:11





You're using SSMS to view it, I assume? The only cases I can think of for that are either somehow your user account doesn't have permission to the table, or you added it recently and haven't refreshed your object list, or you're looking in the wrong copy of the database

– ADyson
Mar 26 at 17:11













Of course you could just open a new query window in your database and write a SELECT statement manually to get the contents of the table. You're not obliged to use the GUI

– ADyson
Mar 26 at 17:12





Of course you could just open a new query window in your database and write a SELECT statement manually to get the contents of the table. You're not obliged to use the GUI

– ADyson
Mar 26 at 17:12













Thanks, I have tired that and it looks like a column has been added to the SiteUsers table called Cause_CauseId and that is updated when the sign button is pressed. Any ideas why this is happening? ID Username Email Password UserImageUrl Cause_CauseId 1 Username1 user1@email.com Password1 /Images/generic-user-icon-19.jpg NULL 2 Username2 user2@email.com Password1 /Images/generic-user-icon-19.jpg 1

– seanrobmaguire
Mar 26 at 17:46





Thanks, I have tired that and it looks like a column has been added to the SiteUsers table called Cause_CauseId and that is updated when the sign button is pressed. Any ideas why this is happening? ID Username Email Password UserImageUrl Cause_CauseId 1 Username1 user1@email.com Password1 /Images/generic-user-icon-19.jpg NULL 2 Username2 user2@email.com Password1 /Images/generic-user-icon-19.jpg 1

– seanrobmaguire
Mar 26 at 17:46












0






active

oldest

votes










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55361254%2fadding-to-a-list-removes-from-another-list%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes




Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.







Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55361254%2fadding-to-a-list-removes-from-another-list%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript