0

I have the following model:

public class Card
{        
    [DataType(DataType.Date)]
    [BindProperty]
    public DateTime Day { get; set; }

    [BindProperty]
    public string Field { get; set; }
}

The following Controller:

// GET: Card
public async Task<IActionResult> Index(DateTime? day)
{
    return View(model);
}

public async Task<IActionResult> Refresh(DateTime? Day, string Field)
{
     return RedirectToAction("Index", Day);
}

The following View:

@model Card

<h1>Cards</h1>
<div class="text-center">
    <label asp-for="Day" class="control-label"></label>
    <input asp-for="Day" class="form-control" />
</div>
<div class="text-center">
    <label asp-for="Field" class="control-label"></label>
    <select asp-for="Field" class="form-control" asp-items="ViewBag.Fields"></select>
</div>
<form asp-action="Refresh">
    @Html.HiddenFor(x => x.Day)
    @Html.HiddenFor(y => y.Field)
    <input type="submit" value="Refresh" class="btn btn-default" />
</form>

No matter what I change, I always get the initial Day value back and null as the Field, like the Model has never been changed…

So how can I post back the modified model to my controller?

1 Answer 1

1

your form is submitting the values from the hidden fields which are rendered on the page when the view first loads and then they are never modified (which is why you are seeing the default initialization for Day and for Field). Your editable fields are outside of the form and are what you're editing but they never get submitted to the server. I think the main takeaway here for you is that forms only know about inputs that exist inside of them (unless you write some javascript magic to handle this but there is no reason to do so in this case)

You need to remove the hidden fields and put your editable fields inside the form as follows:

@model Card

<h1>Cards</h1>

<form method="post" asp-action="Refresh">
    <div class="text-center">
        <label asp-for="Day" class="control-label"></label>
        <input asp-for="Day" class="form-control" />
    </div>
    <div class="text-center">
        <label asp-for="Field" class="control-label"></label>
        <select asp-for="Field" class="form-control" asp-items="ViewBag.Fields"></select>
    </div>

    <input type="submit" value="Refresh" class="btn btn-default" />
</form>

you can also change your controller action to:

[HttpPost]
public async Task<IActionResult> Refresh(Card card)
{
     return RedirectToAction("Index", card.Day);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you are right… I know it was something that should be obvious :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.