Home > front end >  Modal with Parameters still apply changes after beeing canceled
Modal with Parameters still apply changes after beeing canceled

Time:03-02

Following Problem, the code below shows a Modal where I can edit Info about Machines, the problem is that when I apply changes to the parameters in the form, and I hit cancel, the changes will apply to the parameters anyway, so the same as I would hit update.

And maybe its something simple and I just dont see it, im relatively new to C# and Blazor.. Would be very nice if someone could help out :)

private async Task Edit Machine(PhysicalMachineInfo machineInfo)
{
var parameters = new ModalParameters();
parameters.Add(nameof(CreatePhysicalMachineModal.physicalMachine), machineInfo);
var createMachineEntryModal = Modal.Show<CreatePhysicalMachineModal>("Edit MachineInfo",parameters); 
var modalResult = await createMachineEntryModal.Result;

if (!modalResult.Cancelled)
{
_ = LoadMachines();
}
}

CodePudding user response:

You are creating parameters with this line

parameters.Add(nameof(CreatePhysicalMachineModal.physicalMachine), machineInfo);

And sending parameters to modal form with this line of code, and in modal form parameters are bind to input controls

var createMachineEntryModal = Modal.Show<CreatePhysicalMachineModal>("Edit MachineInfo",parameters);

However the objects are passed by reference and any changes made to it's properties by keystrokes or any other means will change object properties in the origin, even if you cancel editing.

One solution to this issue is create a fresh copy of parameters and send it to modal form

You can create copy of machineInfo object like this, using Newtonsoft library or can use any other JSON serializer

 string obj =  Newtonsoft.Json.JsonConvert.SerializeObject(machineInfo);
 copyMachineInfo =  Newtonsoft.Json.JsonConvert.DeserializeObject<PhysicalMachineInfo>(obj);
  • Related