I am new in ASP.NET
and I would like to update SQL object
by user’s id
. I read about Entity Framework
, but I am used to use SqlConnection
. User’s id is valid, because the same Id I am using in same Controller
for different CRUD
action. My problem is that I am still getting 500 Internal Server exception
and I think the main problem is in Controller, especially here in header of the method.
public IActionResult Put(int eventId, [FromBody] Event eventData, int userId)
I would kindly appreciate any help or opinion or setting to the right direction.
[HttpPut]
[Route("/api/calendar/event/put/{eventId}/{userId}")]
// eventId is id of the event I want to update, eventData is object with new
//data to be updated
public IActionResult Put(int eventId, [FromBody] Event eventData, int userId)
{
try
{
eventData.Id = eventId;
events.Update(eventData, userId);
return Ok();
}
catch (InvalidInput ex)
{
// log the exception or return an error response
return StatusCode(StatusCodes.Status400BadRequest, ex.Message);
}
catch (Exception ex)
{
// log the exception or return an error response
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
React component:
const EditEvent = ({ initialValues, handleUpdate, onClose, isOpen, onReload, userId }) => {
const [id, setId] = useState(initialValues?.id || null);
const [eventName, setEventName] = useState(initialValues?.eventName || "");
const [eventDate, setEventDate] = useState(initialValues?.eventDate || "");
const [category, setCategory] = useState(initialValues?.category || "");
const [errorMessage, setErrorMessage] = useState("");
const handleDescriptionChange = (event) => {
setEventName(event.target.value);
};
const handleDateChange = (event) => {
setEventDate(event.target.value);
};
const onUpdate = (updatedEvent) => {
axios
.put(`/api/calendar/event/put/${updatedEvent.id}/${userId}`, updatedEvent)
.then((response) => {
// handle successful response
console.log( "update:"+ updatedEvent.id);
handleUpdate(response.data);
setCategory(1);
})
.catch((error) => {
// handle error response
console.log(error);
});
};
const handleSubmit = (event) => {
event.preventDefault();
if (!eventName || !eventDate) {
setErrorMessage("Please fill all the gaps");
return;
}
const updatedEvent = {
id: initialValues ? initialValues.id : null,
eventName: initialValues.eventName,
eventDate: initialValues.eventDate,
category: 1,
};
console.log("date:" + eventDate);
onUpdate(updatedEvent);
onClose();
onReload();
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="eventName" className="block text-gray-700 font-bold mb-2">
Event Name
</label>
<input
type="text"
id="eventName"
name="eventName"
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
value={eventName}
onChange={handleDescriptionChange}
maxLength={255}
/>
{errorMessage && (
<p className="text-red-500 text-xs italic mt-2">{errorMessage}</p>
)}
<div className="mb-4">
<label htmlFor="eventDate" className="block text-gray-700 font-bold mb-2">
Event Date
</label>
<input
type="date"
id="eventDate"
name="eventDate"
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
value={eventDate}
onChange={handleDateChange}
/>
</div>
<div className="flex justify-end">
<button
type="submit"
className="inline-flex justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-500 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
onClick={(event) => handleSubmit(event, id)}
>
Update
</button>
<button
type="button"
className="ml-2 inline-flex justify-center px-4 py-2 border border-gray-300 rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
onClick={onClose}
>
Cancel
</button>
</div>
</form>
);
Update method:
public void Update(Event eventElemnt, int user_id)
{
if (eventElemnt == null || user_id < 0 || user_id.GetType() != typeof(int))
{
throw new InvalidInput("Invalid inputs");
}
using (SqlConnection conn = new SqlConnection(_configuration.GetConnectionString("Omega_Conn")))
{
query = "UPDATE Event SET event_name = @event_name, event_date = @event_date, fk_event_category = @event_category " +
"WHERE fk_event_user = @user_id ;";
conn.Open();
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.AddWithValue("@event_name", eventElemnt.Event_name);
command.Parameters.AddWithValue("@event_date", eventElemnt.Event_date);
command.Parameters.AddWithValue("@event_category", 1);
command.Parameters.AddWithValue("@user_id", user_id);
command.ExecuteNonQuery();
}
}
}
model Event:
using Omega.Interfaces.Base;
using System;
namespace Omega.Models
{
/// <summary>
/// Represents an event with a name, date, user and category.
/// </summary>
public class Event : IBase
{
/// <summary>
/// Gets or sets the ID of the event.
/// </summary>
public int Id { get ; set ; }
/// <summary>
/// Gets or sets the name of the event.
/// </summary>
public string? Event_name { get; set; }
/// <summary>
/// Gets or sets the date of the event.
/// </summary>
public DateTime Event_date { get; set; }
/// <summary>
/// Gets or sets the ID of the user who created the event.
/// </summary>
public int Fk_event_user { get; set; }
/// <summary>
/// Gets or sets the ID of the category of the event.
/// </summary>
public int Fk_event_category { get; set; }
}
}
2
Answers
The problem was in
handleSubmit
method, where properties did not match properties from modelThen in EditEvent component:
Your issue is on the
handleSubmit
method. You are always sending initial values back in the API call and your property names don’t match:You should change this to send the data collected. I don’t know what
Id
is, so I won’t mess with that, but the name, date and category:You are seeing this error because by not passing a value (your initial
eventDate
value is an empty string), your server side object’s property (which is not nullable) is defaulting to the min C# value for aDateTime
object which isJanuary 1, 0001 00:00:00
. SQL server’s minimum date value isJanuary 1, 1753
, thereby causing an overflow error.