Losing data during transfer from one action to another - c#

I'm losing data during transfer from one action to another
What's wrong? I'm doing this:
public ActionResult Index(CV model)
{
return View();
}
public ActionResult rr()
{
CV _cv = new CV();
_cv.education = new List<Education>();
_cv.education.Add(new Education()
{
Faculty = "sa",
OnGoing = false,
Specialization = "asdasd",
UniversityName = "sulxan",
EndDate = DateTime.Now.AddDays(1),
StartDate = DateTime.Now
});
return RedirectToAction("Index", _cv);
}
And when I'm debugging to Index parameter model.education.count = 0 instead of 1. In rr action it's 1 with desired values.
My model class is:
public class CV
{
public List<Education> education { get; set; }
public Education newEducation { get; set; }
}
public class Education
{
public string UniversityName { get; set; }
public string Faculty { get; set; }
public string Specialization { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool OnGoing { get; set; }
}

Posting an answer because I'm too much of a noob to comment.
What Stephen Muecke said in his comment is totally correct - and, it's definitely important to persist your data. One other thing to note is that, based on the code you posted, you don't need the RedirectToAction if all you are trying to do is return the model with the view you want:
return View("Index", _cv);
Of course, without seeing how the rest of your app is built, that could potentially cause an issue.

You can use tempdata to store the entity and retrieve the data.use this code
public ActionResult Index()
{
CV model = (CV)TempData["cv"];
return View();
}
public ActionResult rr()
{
CV _cv = new CV();
_cv.education = new List<Education>();
_cv.education.Add(new Education()
{
Faculty = "sa",
OnGoing = false,
Specialization = "asdasd",
UniversityName = "sulxan",
EndDate = DateTime.Now.AddDays(1),
StartDate = DateTime.Now
});
TempData["cv"] = _cv;
return RedirectToAction("Index");
}

You can use tempdata
like this
public ActionResult Index()
{
var model = TempData["CV "] as CV;
return View();
}
public ActionResult rr()
{
CV _cv = new CV();
_cv.education = new List<Education>();
_cv.education.Add(new Education()
{
Faculty = "sa",
OnGoing = false,
Specialization = "asdasd",
UniversityName = "sulxan",
EndDate = DateTime.Now.AddDays(1),
StartDate = DateTime.Now
});
TempData["CV"] = _cv;
return RedirectToAction("Index");
}

Related

ASP.NET C# inserting multiple values in single field in MongoDB

I am trying to store names of team members of a project in the same field in MongoDB using ASP.NET.
The value is read correctly but I am having trouble creating a new entry.
Below is my controller. Simply writing the document.insert() doesn't work as it only stores a single value and not a list.
public ActionResult InsertProject(Projectdata model)
{
_dbContext = new MongoContext();
if (Request.Cookies["Userdata"] == null)
{
return this.RedirectToAction("Index", "User");
}
var document2 = _dbContext._database.GetCollection<Mongodata>("mainuser_data");
var users = document2.FindAll().ToList();
var document = _dbContext._database.GetCollection<ProjectItem>("project_data");
string project = model.pname;
var query = Query<ProjectItem>.EQ(model2 => model2.pname, project);
var count = document.FindAs<ProjectItem>(query).Count();
if (count == 0)
{
var result = document.Insert(model);
TempData["Message"] = "Project Added";
return View();
}
else
{
TempData["Message"] = "Project Already Exists";
return View("Insert", model);
}
}
My model:
public class Projectdata
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("pname")]
public string pname { get; set; }
[BsonElement("pdesc")]
public string pdesc { get; set; }
[BsonElement("sdate")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
public DateTime sdate { get; set; }
[BsonElement("edate")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
public DateTime edate { get; set; }
public List<Team2> teams { get; set; }
[BsonElement("leader")]
public string leader { get; set; }
}
public class Team2
{
[BsonElement("username")]
public string username { get; set; }
}
I can read all multiple values fine but creating a new entry is where I am facing trouble.
Below is the sample data to be added:
{
"_id" : ObjectId("5f93cf48a591c562654d4ded"),
"pname" : "demo1",
"pdesc" : "this is a demo project",
"sdate" : "24-10-2020",
"edate" : "25-10-2020",
"teams" : [
{
"username" : "ManushPandya"
},
{
"username" : "KuntalVakil"
}
],
"leader" : "ManushPandya"
}
How do I store multiple values in teams field? I am using check boxes to let user select those multiple values in a view.

How do i confirm the action delete(POST) in my controller?

I have a ViewModel and I would like to make a fonctionnal delete(GET) and deleteConfirmed(POST) so i can delete what ever data is stored in my DB
I don’t know and would like to know what step to take to complete the deleteConfirmed. There is normally auto-generated code but it’s not what I need.
here is my ViewModel
using System;
using ExploFormsDB.Models;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ExploFormsDB.ViewModels
{
public class WorkShiftDetailViewModel
{
[Key]
public int WorkShiftId { get; set; }
public int? HoleId { get; set; }
public string HoleName { get; set; }
public int SurveyLocationId { get; set; }
public int SupplierId { get; set; }
public int ZoneId { get; set; }
public string SurveyLocation1 { get; set; }
public string SupplierName { get; set; }
public string ZoneName { get; set; }
public DateTime StartDay { get; set; }
public DateTime EndDay { get; set; }
public ICollection<WorkerViewModel> WorkShiftEmployees { get; set; }
}
}
Here is my Controller, i have included the Create to help have a better understanding. GET: Delete seems to be working correctly, i am having trouble with the Post. any help what so ever will do. if the question as been answered already please send me a link. I'm pretty new to c# and core and completly new to ViewModels
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(WorkShiftDetailViewModel workShiftDetailViewModel)
{
if (!ModelState.IsValid)
{
WorkShift ws = new WorkShift();
ws.StartDay = workShiftDetailViewModel.StartDay;
ws.EndDay = workShiftDetailViewModel.EndDay;
ws.SupplierId = workShiftDetailViewModel.SupplierId;
ws.SurveyLocationId = 1;
ws.ZoneId = workShiftDetailViewModel.ZoneId;
ws.HoleId = workShiftDetailViewModel.HoleId;
_context.Add(ws);
await _context.SaveChangesAsync();
foreach (WorkerViewModel member in workShiftDetailViewModel.WorkShiftEmployees)
{
if (member.isDeleted == false) {
WorkShiftTeam emp = new WorkShiftTeam();
emp.EmployeeId = member.EmployeeId;
emp.RoleId = member.RoleId;
emp.WorkShiftId = ws.WorkShiftId;
_context.Add(emp);
}
}
HttpContext.Session.SetInt32("wsId", ws.WorkShiftId);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(CreateSharedView));
}
return View(workShiftDetailViewModel);
}
public IActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
List<WorkerViewModel> Workers = new List<WorkerViewModel>();
WorkShift ws = _context.WorkShift.Include(w => w.WorkShiftTeam).SingleOrDefault(x => x.WorkShiftId == id);
WorkShiftDetailViewModel detail = new WorkShiftDetailViewModel();
detail.HoleName = ws.HoleId == null ? "N/A" : _context.Hole.Find(ws.HoleId).HoleName;
detail.StartDay = ws.StartDay;
detail.EndDay = ws.EndDay;
detail.ZoneName = _context.Zone.Find(ws.ZoneId).ZoneName;
detail.SurveyLocation1 = _context.SurveyLocation.Find(ws.SurveyLocationId).SurveyLocation1;
detail.SupplierName = _context.Supplier.Find(ws.SupplierId).SupplierName;
detail.WorkShiftId = ws.WorkShiftId;
int order = 0;
var rolelist = new SelectList(_context.Role, "RoleId", "Role1");
var empsWithFullName = from e in _context.Employee.Where(a => a.IsActive)
select new
{
ID = e.EmployeeId,
FullName = e.LastName + ", " + e.FirstName
};
var empList = new SelectList(empsWithFullName, "ID", "FullName");
foreach (WorkShiftTeam member in ws.WorkShiftTeam.OrderBy(a => a.EmployeeId))
{
Workers.Add(new WorkerViewModel() { EmployeeId = member.EmployeeId, RoleId = member.RoleId, Index = order, Roles = rolelist, Employees = empList });
order++;
}
detail.WorkShiftEmployees = Workers;
return View(detail);
}
// POST: WorkShiftDetailViewModels/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
//??
} ```
Why you created an extra method for delete action as HttpGet? (that occurred conflict)
change it to:
[HttpGet]
public IActionResult GetById(int? id) { ... }
and just one delete method with this definition
[HttpPost]
public async Task<IActionResult> Delete(int? id) { ... }

How to determine whether a model is valid?

I am having some trouble here. The situation is to update an existing record, at the same time, save a new row if there is no record by searching first the table.
When I am saving a new record, there is no problem. But when I'm trying to update an existing one, there are no changes. I tried to place some breakpoints specifically on the code that do the thing. It just ending up on the line if(!ModelState.IsValid).
Note:
Some of the lines are hard-coded for the sake of having some dummy data.
Function for retrieving some data from DB to pass to view model
[HttpGet]
public ActionResult CardNumberAssignment(string empId, int cardNumberId)
{
var getIdDetails = dbContext.CardNumberAssignments.Where(c => c.CardNumberId == cardNumberId && c.IsActive == true).SingleOrDefault();
if (cardNumberId == 0) //EMPLOYEE HAS NO CARD NUMBER YET
{
var viewModel = new CardNumberQRCodeVM
{
CardNumberId = 0,
CMId = empId,
OldQRCode = "No QR Code history",
OldReservedCardNumber = "No Card Number history",
NewReservedCardNumber = GetRandomCardNumber()
};
return View(viewModel);
}
else
{
if (getIdDetails.CMId != empId) //JUST CHECKING IF THE EMPLOYEE HAS THE CORRECT CARDNUMBERID FROM DB
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var empCardDetails = dbContext.CardNumberAssignments
.Include(c => c.ReservedCardNumber)
.Where(emp => emp.CMId == empId && emp.IsActive == true)
.Select(fields => new CardNumberQRCodeVM
{
CardNumberId = fields.CardNumberId,
CMId = empId,
OldQRCode = fields.QRCode,
IsActive = fields.IsActive,
OldReservedCardNumber = fields.ReservedCardNumber.CardNumber,
}).FirstOrDefault();
empCardDetails.NewReservedCardNumber = GetRandomCardNumber();
return View(empCardDetails);
}
}
Function for adding/editing record
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveIdInformation(CardNumberQRCodeVM vm)
{
if (!ModelState.IsValid)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// JUST ADDING/EDITING SOME CARD NUMBERS....
else
{
if (vm.CardNumberId == 0) //INSERT A NEW ROW FOR NEW CARD NUMBER AND QR CODE
{
var newCardNumber = new ReservedCardNumber
{
CardNumber = vm.NewReservedCardNumber,
IsActive = true,
CreatedDate = DateTime.Now,
CreatedBy = "Paolo",
ModifiedDate = DateTime.Now,
ModifiedBy = "Paolo"
};
dbContext.ReservedCardNumbers.Add(newCardNumber);
var newIdInfo = new CardNumberAssignment
{
CardNumberId = newCardNumber.Id,
QRCode = vm.NewQRCode,
CMId = vm.CMId,
IsActive = true,
CreatedDate = DateTime.Now,
CreatedBy = "Paolo",
ModifiedDate = DateTime.Now,
ModifiedBy = "Paolo"
};
dbContext.CardNumberAssignments.Add(newIdInfo);
}
else // EDIT EXISTING
{
var getEmployeeIdInDb = dbContext.CardNumberAssignments.Single(e => e.Id == vm.CardNumberId);
getEmployeeIdInDb.ReservedCardNumber.CardNumber = vm.NewReservedCardNumber;
getEmployeeIdInDb.QRCode = vm.NewQRCode;
getEmployeeIdInDb.IsActive = true;
getEmployeeIdInDb.ModifiedDate = DateTime.Now;
getEmployeeIdInDb.ModifiedBy = "Paolo";
}
dbContext.SaveChanges();
}
return RedirectToAction("CMDetails", "Admin", new { #empId = vm.CMId });
}
View model
public class CardNumberQRCodeVM
{
public int CardNumberId { get; set; }
public string CMId { get; set; }
[Display(Name = "Existing QR Code")]
public string OldQRCode { get; set; }
[Required]
[Display(Name = "New QR Code")]
public string NewQRCode { get; set; }
[Display(Name = "Resigned Cast Member?")]
public bool IsActive { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
public ReservedCardNumber ReservedCardNumber { get; set; }
[Display(Name = "Old Card Number")]
public string OldReservedCardNumber { get; set; }
[Display(Name = "New Card Number")]
public string NewReservedCardNumber { get; set; }
}

Import the values stored in the database from the controller

[HttpGet]
public ActionResult Create()
{
Articles article = new Articles();
return View(article);
}
[HttpPost]
public ActionResult Create(Articles article)
{
try
{
article.Family = article.ArticleIDX; //그룹번호
article.Parent = 0; //순서
article.Depth = 1; //그룹내 최상위 글로부터 매겨지는 순서
article.Indent = 0; //들여쓰기
article.ModifyDate = DateTime.Now;
article.ModifyMemberID = User.Identity.Name;
db.Articles.Add(article);
db.SaveChanges();
if (Request.Files.Count > 0)
{
var attachFile = Request.Files[0];
if (attachFile != null && attachFile.ContentLength > 0)
{
var fileName = Path.GetFileName(attachFile.FileName);
var path = Path.Combine(Server.MapPath("~/Upload/"), fileName);
attachFile.SaveAs(path);
ArticleFiles file = new ArticleFiles();
file.ArticleIDX = article.ArticleIDX;
file.FilePath = "/Upload/";
file.FileName = fileName;
file.FileFormat = Path.GetExtension(attachFile.FileName);
file.FileSize = attachFile.ContentLength;
file.UploadDate = DateTime.Now;
db.ArticleFiles.Add(file);
db.SaveChanges();
}
}
ViewBag.Result = "OK";
}
catch (Exception ex)
{
Debug.WriteLine("Board");
Debug.WriteLine(ex.ToString());
ViewBag.Result = "FAIL";
}
return View(article);
//return RedirectToAction("ArticleList");
}
[HttpGet]
public ActionResult ReplyCreate(int aidx)
{
Articles articleReply = new Articles();
return View(articleReply);
}
[HttpPost]
public ActionResult ReplyCreate(Articles replyArticles)
{
Articles articles = new Articles();
try
{
//부모글 불러오기(글번호로 불러오기)
Articles note = db.Articles.Find(articles.ArticleIDX);
//Family는 원글의 번호
replyArticles.Family = replyArticles.ArticleIDX;
//Parent 순서
//Depth 는 답글의 글 번호
//Indent 들여쓰기
replyArticles.ModifyDate = DateTime.Now;
replyArticles.ModifyMemberID = User.Identity.Name;
db.Articles.Add(replyArticles);
db.SaveChanges();
ViewBag.Result = "OK";
}
catch (Exception ex)
{
ViewBag.Result = "FAIL";
}
return View(replyArticles);
}
public partial class Articles
{
[Key]
public int ArticleIDX { get; set; }
public int? Family { get; set; }
public int? Depth { get; set; }
public int? Indent { get; set; }
public int? Parent { get; set; }
[StringLength(200)]
public string Title { get; set; }
[Column(TypeName = "text")]
public string Contents { get; set; }
[StringLength(50)]
public string Category { get; set; }
[StringLength(20)]
public string ModifyMemberID { get; set; }
public DateTime? ModifyDate { get; set; }
public virtual Members Members { get; set; }
}
The above code is the code I implemented.
Articles created using the create method are stored in the database.
What do you do when you try to recall a post stored in the database with ReplyCreate?
The null value is often entered into the model.
I try to find it using the primary key, but the primary key also has a null value.
Articles note = db.Articles.Find(articles.ArticleIDX);
does not work because articles is an empty object, due to the line
Articles articles = new Articles();
just above. You never set any of the fields in this object, including the ArticleIDX, before calling the Find method.
I think you probably intended to search using the value passed in to the controller? In that case it would need to be
Articles note = db.Articles.Find(replyArticles.ArticleIDX);
because replyArticles is the variable which was received from the browser in the request. I assume this contains a value in the ArticleIDX field.
Having said that, I don't know what the purpose of this line of code is, because you never use the note object in any of the following code, so I don't know why you needed to find it.

Request.CreateResponse returns blank data to postman

I have encountered a problem when trying to call my web api with a post request, a empty array is returned.
My method is:
// POST: Api/v1/transaction/
[HttpPost]
public HttpResponseMessage Post(string user)
{
var userId = new Guid(user);
var transactions = new Collection<TransactionDataTransferObject>();
try
{
var seller = _databaseContext.Sellers.Single(s => s.Id == userId);
var sellerMedias = _databaseContext.Medias.Where(m => m.TakenBy.Id == seller.Id);
foreach (var sellerMedia in sellerMedias)
{
var allLogsForMedia = _databaseContext.Logs.Where(l => l.ObjectReferenceId == sellerMedia.Id);
foreach (var logMedia in allLogsForMedia)
{
var transaction = new TransactionDataTransferObject
{
Date = logMedia.DateTimeInUtc,
Amount = sellerMedia.PriceInSek,
MediaName = sellerMedia.FileName,
UserName = seller.FirstName + " " + seller.LastName
};
transactions.Add(transaction);
}
}
}
catch (Exception exception)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, exception);
}
return Request.CreateResponse(HttpStatusCode.OK, transactions);
}
When I debug transactions variable, I see two objects in the collection.
My response to postman is
[
{},
{}
]
What have I done wrong? Where is my data which is sent?
Ok, after some hours of slaming my head in the table i found out that I used
[DataContract] as filter on the ViewModel,TransactionDataTransferObject.
Like this:
[DataContract]
public class TransactionDataTransferObject
{
[Display(Name = "Date")]
public DateTime Date { get; set; }
public string MediaName { get; set; }
public Guid MediaId { get; set; }
public string UserName { get; set; }
public Guid UserId { get; set; }
[Display(Name = "Description")]
public string Discriminator { get; set; }
[Display(Name = "Amount")]
public decimal Amount { get; set; }
}
Which was wrong in this case...
Thanks for reading!

Categories