morry329#
morry329#
CC#
Created by morry329# on 2/13/2025 in #help
Id points to always null
I have an Edit method which always returns a null id: https://pastecode.io/s/upokmghg I tried to map the Id (from the controller/model) on my cshtml but it did not help. Could anyone kindly point me in the right direction??
7 replies
CC#
Created by morry329# on 2/8/2025 in #help
The edit method does not edit the pre-existing data but it creates a new data entry with NULL
No description
26 replies
CC#
Created by morry329# on 2/6/2025 in #help
InvalidCastException: Unable to cast object of type
The full exception reads InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1[WebApplication1.Models.ListingProjectsDTO]' to type 'System.String'. The exception points at this method
public async Task<IActionResult> TestDashboard1()
{
var datasource = _context.ListingDTO_DBTable.AsQueryable();
var query = datasource
.Select(x => new ListingProjectsDTO() {
Id = x.Id,
ListingName = x.ListingName,
});
ConvertFromDBVal<string>(query);
var listings = await query.ToListAsync();


return View(listings);
}

public static T ConvertFromDBVal<T>(object obj)
{
if (obj == null || obj == DBNull.Value)
{
return default(T);
}
else
{
return (T)obj; //InvalidCastException
}
}
public async Task<IActionResult> TestDashboard1()
{
var datasource = _context.ListingDTO_DBTable.AsQueryable();
var query = datasource
.Select(x => new ListingProjectsDTO() {
Id = x.Id,
ListingName = x.ListingName,
});
ConvertFromDBVal<string>(query);
var listings = await query.ToListAsync();


return View(listings);
}

public static T ConvertFromDBVal<T>(object obj)
{
if (obj == null || obj == DBNull.Value)
{
return default(T);
}
else
{
return (T)obj; //InvalidCastException
}
}
` I am not good at casting at all, I have tried return (System.string) obj. I tried to create a list with System.string data type with the help of foreach in the TestDashboard1(). Those of course failed. Could anyone kindly point me in the right direction? PS: if anyone is wondering why I am using the generic method here, see https://stackoverflow.com/questions/870697/unable-to-cast-object-of-type-system-dbnull-to-type-system-string
3 replies
CC#
Created by morry329# on 1/30/2025 in #help
✅ NullPointException in the Update/Post method, but not in the Get Method
I started feeling puzzled at this NullPointException in this code
[HttpGet]
public IActionResult EditListingJ(int? Id)
{
try
{
var ListingDTO_DBTable = _context.ListingDTO_DBTable.Find(Id);
if (ListingDTO_DBTable != null)
{
ListingProjectsDTO dtoModelEdit = new ListingProjectsDTO()
{
Id = ListingDTO_DBTable.Id,
ListingName = ListingDTO_DBTable.ListingName
};
Console.WriteLine($"Got it"); //The GET method is fine, it grabs the id
return Json(dtoModelEdit);
}

return Json(null);

}
catch (Exception ex)
{

return null;
}
}

[HttpPost]
public IActionResult EditListingJ(ListingProjectsDTO editedDtoModel)
{
if (ModelState.IsValid)
{
//NullPointException!! why does this line stay always null, I don't understand
ListingProjectsDTO _listingProjectsDtoEdit = _listingProjectsDtoRepository.getListingProjectsDto(editedDtoModel.Id);
_listingProjectsDtoEdit.Id = editedDtoModel.Id;
_listingProjectsDtoEdit.ListingName = editedDtoModel.ListingName;
_context.ListingDTO_DBTable.Update(_listingProjectsDto);
_context.SaveChanges();
return Json(_listingProjectsDto);


}
return Json(null);
}
[HttpGet]
public IActionResult EditListingJ(int? Id)
{
try
{
var ListingDTO_DBTable = _context.ListingDTO_DBTable.Find(Id);
if (ListingDTO_DBTable != null)
{
ListingProjectsDTO dtoModelEdit = new ListingProjectsDTO()
{
Id = ListingDTO_DBTable.Id,
ListingName = ListingDTO_DBTable.ListingName
};
Console.WriteLine($"Got it"); //The GET method is fine, it grabs the id
return Json(dtoModelEdit);
}

return Json(null);

}
catch (Exception ex)
{

return null;
}
}

[HttpPost]
public IActionResult EditListingJ(ListingProjectsDTO editedDtoModel)
{
if (ModelState.IsValid)
{
//NullPointException!! why does this line stay always null, I don't understand
ListingProjectsDTO _listingProjectsDtoEdit = _listingProjectsDtoRepository.getListingProjectsDto(editedDtoModel.Id);
_listingProjectsDtoEdit.Id = editedDtoModel.Id;
_listingProjectsDtoEdit.ListingName = editedDtoModel.ListingName;
_context.ListingDTO_DBTable.Update(_listingProjectsDto);
_context.SaveChanges();
return Json(_listingProjectsDto);


}
return Json(null);
}
` In the Get method it grabs the id but the following Post method it does not and crashes into NullPointException. Seems to me like the GET method was able to refer to the row existing in my DB. However that does not seem to be the case for the Post method. Could anyone help me understand why? My code: https://pastebin.com/pXHYHfKM
46 replies
CC#
Created by morry329# on 1/17/2025 in #help
edited data/user input not saved in db
No description
1 replies
CC#
Created by morry329# on 1/3/2025 in #help
The app does not allow edits to the pre-existing card view contents
No description
2 replies
CC#
Created by morry329# on 12/23/2024 in #help
Unable to create an object of type 'JsonContext'
I have fought this error for about an hour and finally gave up - would like a second set of eyes. I wanted to use dotnet ef migrations add InitialCreate which prompted this error Could you kindly point me in the right direction? https://pastebin.com/GuxUApaW
8 replies
CC#
Created by morry329# on 12/21/2024 in #help
✅ System.InvalidOperationException: No database provide has been configured for this DbContext
It is all about this newbie error
System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
I have no clue what triggered all this. Could kindly point me in the right direction? https://pastebin.com/RbkExv6j This is full code and full exception message for your reference.
7 replies
CC#
Created by morry329# on 12/19/2024 in #help
Edit view directs to 404 not found
A beginner's mistake - the problem is that i have been getting Site Not Found 404 error (as per screenshot) while I wanted to display the edit dashboard view on localhost:https://imgur.com/a/mw5wBkD i think the connection between my view (html and js) and controller has gone wrong: https://pastebin.com/n4cfnwLp Could anyone kindly point out what I have been missing out here?
6 replies
CC#
Created by morry329# on 12/1/2024 in #help
Edit function does not work
So I would like a second set of eyes. I wanted to try editing the pre-existing record on my card view (see the screenshot attached) like Beachfront Villa -> Beachfront Villa 8. Even this easy modification does not succeed, as on clicking the save button I got "record not found" And this comes from here in the controller
[HttpPost]
public async Task<IActionResult> Update(ListingProjects updatedUserModelRef)
{


if (oldListingProjects == null)
{
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
return Json(new { success = false, message = "Record not found." }); //this is the error i see on View
}
return NotFound();
}
[HttpPost]
public async Task<IActionResult> Update(ListingProjects updatedUserModelRef)
{


if (oldListingProjects == null)
{
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
return Json(new { success = false, message = "Record not found." }); //this is the error i see on View
}
return NotFound();
}
and this is what the frontend devtool says: https://imgur.com/a/xs8LLlD my database has not the id "1" referred in that devtool:
mysql> Select * from ListingDBTable;
+----+----------------------+----------------------------------+------------+------------+
| Id | ListingName | ImageUrl | CategoryId | LocationId |
+----+----------------------+----------------------------------+------------+------------+
| 5 | Beachfront Villa | http://example.com/villa.jpg | 1 | 1 |
| 6 | hidden moon building | hiddenmoon | 1 | 1 |
| 74 | New Listing | http://example.com/new_image.jpg | 1 | 1 |
+----+----------------------+----------------------------------+------------+------------+
mysql> Select * from ListingDBTable;
+----+----------------------+----------------------------------+------------+------------+
| Id | ListingName | ImageUrl | CategoryId | LocationId |
+----+----------------------+----------------------------------+------------+------------+
| 5 | Beachfront Villa | http://example.com/villa.jpg | 1 | 1 |
| 6 | hidden moon building | hiddenmoon | 1 | 1 |
| 74 | New Listing | http://example.com/new_image.jpg | 1 | 1 |
+----+----------------------+----------------------------------+------------+------------+
` my save button on View should have been picking up any ids listed here (5,6, or 74) but as the devtool shows it picks up 1 instead. i suppose if it picks up 5,6,74 it will let me edit the ListingName property. so could anyone kindly point me in the right direction? Relevant code snippets here https://pastebin.com/9U9zjvaG
20 replies
CC#
Created by morry329# on 11/29/2024 in #help
✅ always gets the invalid data received
I have been creating a simple CRUD app with the ASP.NET. My update function does not work as expected: the save button triggers the error message "invalid data received" ; somehow the model reference is considred null on clicking the save button

//clicking the save btn prompts this method to work
public async Task<IActionResult> Update(ListingProjects updatedUserModelRef)
{
if (updatedUserModelRef == null || updatedUserModelRef.ListingName == null)
{
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
return Json(new { success = false, message = "Invalid data received." }); //however it always falls into this invalid message..
}
return NotFound();
}

//clicking the save btn prompts this method to work
public async Task<IActionResult> Update(ListingProjects updatedUserModelRef)
{
if (updatedUserModelRef == null || updatedUserModelRef.ListingName == null)
{
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
return Json(new { success = false, message = "Invalid data received." }); //however it always falls into this invalid message..
}
return NotFound();
}
could anyone kindly advice me on why the save button does not save the user input as expected? the full code here https://pastebin.com/4C2aYF78
2 replies
CC#
Created by morry329# on 11/11/2024 in #help
Insert Method does not insert or save the user input as wanted
I have a working UI with a text field to enter a property name like "Ca* Oro Bridge" on my MVC view. The save button is also displayed on the view. Onclick it does not save the userinput in the text field (henceforth it is also not saved in the DB). I have debugged the follwing code responsible for handling user inputs
public IActionResult InsertListings()
{
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult InsertListings([Bind("ListingName")] ListingProjects listingProject) // Change to ListingProjects model
{

try
{
if (ModelState.IsValid)
{
_context.ListingDBTable.Add(listingProject);
_context.SaveChanges();
return RedirectToAction("TestDashboard1"); // Redirect to dashboard
}
else
{
// Model is invalid, handle it (e.g., show validation errors)
return View(listingProject); // Return the view with error messages
}
}
catch (DbUpdateException dbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}

return View(listingProject);
}
public IActionResult InsertListings()
{
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult InsertListings([Bind("ListingName")] ListingProjects listingProject) // Change to ListingProjects model
{

try
{
if (ModelState.IsValid)
{
_context.ListingDBTable.Add(listingProject);
_context.SaveChanges();
return RedirectToAction("TestDashboard1"); // Redirect to dashboard
}
else
{
// Model is invalid, handle it (e.g., show validation errors)
return View(listingProject); // Return the view with error messages
}
}
catch (DbUpdateException dbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}

return View(listingProject);
}
` I am not versed in the world of debugging, but it looks like the HttpGet method refers or returns null. InsertListing method (HttpPost method) deems it as !ModelState.Isvalid (which means my code does not save the input at all) Now I don't quite understand what caused all this null and invalidity. https://pastebin.com/DhCg4Md2 Can anyone kindly point me in the right direction?
1 replies
CC#
Created by morry329# on 11/8/2024 in #help
Save button does not save the inserted data
No description
15 replies
CC#
Created by morry329# on 11/4/2024 in #help
OnClick delete button directs to 404 Error
No description
1 replies
CC#
Created by morry329# on 11/3/2024 in #help
Does this make sense? |
No description
5 replies
CC#
Created by morry329# on 10/13/2024 in #help
my MVC view thinks my model is null!
No description
1 replies
CC#
Created by morry329# on 10/7/2024 in #help
Not found 404 at await fetch
No description
6 replies
CC#
Created by morry329# on 9/30/2024 in #help
Does it make sense to two references (to database migration and data seeding) in the same using
I am totally new to this, so I rely on chatGPT a lot With the help of GPT I have wrote a code like this
var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Database.Migrate();
var services = scope.ServiceProvider;

var seeder = new DataSeed(db);
seeder.SeedModels();
}
var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Database.Migrate();
var services = scope.ServiceProvider;

var seeder = new DataSeed(db);
seeder.SeedModels();
}
As you see this is the Program.cs snippet (ASP.NET Core 7). My concern is that this code might make no sense to have db.Database.Migrate(); and seeder.SeedModels(); under the same roof (the same using). I don't know much about all this ASP.NET world but I migrated database a couple of times via the commandline like dotnet ef add-migration etc. so I started wondering if db.Database.Migrate(); in Program.cs makes any sense.
What do you all think of this snippet?
6 replies
CC#
Created by morry329# on 9/24/2024 in #help
created a new view but that view only outputs the html (of the login page!)
No description
23 replies
CC#
Created by morry329# on 9/18/2024 in #help
MySqlException: Column 'Age' cannot be null
So this error occured in the following scenario: I have created a simple ASP.NET Core web app with some simple db configurations. On running dotnet run from Rider, the browser displayed my web app (a login form). I have click "register a new user". Then I was redirected to a register form page with three textfields , email, password and repeat password. I filled in all of them and hit register. Now I was bugged with this bunch of exception texts https://pastebin.com/7DqbUai5 I don't understand this error Column 'Age' cannot be null. I made extra sure that my DB has the column Age with non-null values like this:
mysql> SELECT * FROM PortalUsers;
+---------------+------+-------------+-------------------------------------------------+
| Name | Age | Location | DisplayInfo |
+---------------+------+-------------+-------------------------------------------------+
| Alice Smith | 30 | New York | Name: Alice Smith Age: 30 Location: New York |
| Bob Johnson | 25 | Los Angeles | Name: Bob Johnson Age: 25 Location: Los Angeles |
| Charlie Brown | 35 | Chicago | Name: Charlie Brown Age: 35 Location: Chicago |
+---------------+------+-------------+-------------------------------------------------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM PortalUsers;
+---------------+------+-------------+-------------------------------------------------+
| Name | Age | Location | DisplayInfo |
+---------------+------+-------------+-------------------------------------------------+
| Alice Smith | 30 | New York | Name: Alice Smith Age: 30 Location: New York |
| Bob Johnson | 25 | Los Angeles | Name: Bob Johnson Age: 25 Location: Los Angeles |
| Charlie Brown | 35 | Chicago | Name: Charlie Brown Age: 35 Location: Chicago |
+---------------+------+-------------+-------------------------------------------------+
3 rows in set (0.00 sec)
` For your reference this is the link to the codes https://pastebin.com/k88fKn7r Could anyone point me in the right direction? I want to solve this error but I need another set of eyes PS: I am just thinking that this error may refer to the column Age which belongs to another table from another DB. The output displayed here came from the table PortalUser in the searchhome DB, but I may have another PortalUser table in my second DB. If that is the case will this error point to that another PortalUser which may have no column values? Hope all this makes sense.
7 replies