Firstly,you need define the property as type List<T>
.
Secondly,not sure how did you get the ScheduledTask
object,but if you get the object by parameter,you need use [Bind(Prefix = "ScheduledTask")]
to specify the suffix,because the name of the select is ScheduledTask.SelectedDays
.
Here is the working demo:
Model:
public class ScheduledTask
{
public List<string> SelectedDays { get; set; }
}
cshtml.cs(You could use BindProperty
to auto get the data from frontend):
public class IndexModel : PageModel
{
public void OnGet()
{
}
[BindProperty]
public ScheduledTask ScheduledTask { get; set; }
public void OnPost()
{
}
}
Result:
Another way:
cshtml.cs:
public class IndexModel : PageModel
{
public void OnGet()
{
}
public ScheduledTask ScheduledTask { get; set; }
public void OnPost([Bind(Prefix = "ScheduledTask")]ScheduledTask model)
{
}
}
Result:
Update:
If you do not want to change the model property type,you could custom model binder:
public class CustomModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var modelName = bindingContext.ModelName;
// Try to fetch the value of the argument by name
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
string combindedString = string.Join(",", valueProviderResult.ToArray());
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
// Check if the argument value is null or empty
if (string.IsNullOrEmpty(combindedString))
{
return Task.CompletedTask;
}
bindingContext.Result = ModelBindingResult.Success(combindedString);
return Task.CompletedTask;
}
}
Model:
public class ScheduledTask
{
[ModelBinder(BinderType = typeof(CustomModelBinder))]
public string SelectedDays { get; set; }
}
And be sure specify the name(add name="SelectedDays"
):
<select id="daySelector" size="7" multiple="multiple" name="SelectedDays" asp-for="ScheduledTask.SelectedDays"
asp-validation-for="ScheduledTask.SelectedDays"
class="form-control">
<option value="1">Monday</option>
//...
</select>
Result:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…