Home > Enterprise >  .NET Core razor submit hidden list in form to controller model
.NET Core razor submit hidden list in form to controller model

Time:01-24

I have a model which containst an object list. I want to hide this list on the form and when I submit it, I want to pass the whole model to the controller which includes the mentioned list as well.

I tried multiple ways to do it but all of them were incorrect for me, did a lot of research tbh.

I have the following model which is displayed on the view:

public class ChangeRequestGeneralViewModel
{
    public string TargetId { get; set; }
    public bool HasValue { get; set; }
    public List<object> OldValues { get; set; }
    public object OldValueType { get; set; }
    public List<object> NewValues { get; set; }
    public object NewValueType { get; set; }
    public string Description { get; set; }
    public List<string> ValueTitle { get; set; }
}

Every time I want to hide the OldValues or NewValues list, the controller model's lists will return null or an empty list. I get the other values correctly in the model, only those 2 properties will be null or empty list.

I tried to return it this way:

<input type="hidden" asp-for="NewValues[i]" />
<input type="hidden" asp-for="NewValues" />

I also tried the followings and these didn't work as well:

@HiddenFor(x => x.NewValues)
@HiddenFor(x => x.NewValues[i])
@EditorFor(x => x.NewValues)
@EditorFor(x => x.NewValues[i])

CodePudding user response:

Have you tried

<input type="hidden" name="OldValues" value="@Model.OldValues" />

also if this is contained within a form ensure this is within that form area. Then when you click submit, using the Model name as the inpput name, it should bind correctly.

Let me know if this works

CodePudding user response:

The problem was the object-type list. Couldn't bind to the data to the model. If I give it a normal type like DateTime, then in that case it'll bind it correctly.

The proper way to do it was creating a custom binding model.

  •  Tags:  
  • Related