iCV
iCV

Reputation: 607

ASP.Net MVC Passing value to controller without dedicated button

I'm trying to pass a value from my ViewModel to a postmethod, which takes 2 filters (one for type, one for difficulty) from a select list and the id of the member whose lessons are being filtered. The id of the member has to get passed to the HttpPost method, so that the filterByDifficulty methods know the maximum difficulty the member is allowed to get.

In short: My get method creates a viewmodel. I pass the viewmodel to the view, but I can't figure out how to pass a certain property from the viewmodel to the post method, without showing it to the user/creating a seperate button.

Controller
The id parameter is what I'm stuck at, I'm trying to figure out how I can pass it to this method, through the view.

[HttpPost]
public IActionResult LessonsForMember(string filter, string filter2, int id)
        {
            Person person = _personRepository.GetBy(id);
            string Difficulty = person.Difficulty.DifficultyString;
                        PersonLessonModel plm = new PersonLessonModel
            {
                Person = person,
                Types = _lessonRepository.GetTypesLimitedByDifficultyAsSelectList(Difficulty),
                Difficulties = _lessonRepository.GetDifficultiesLimitedByDifficultyAsSelectList(Difficulty),
                Lessons = _lessonRepository.GetFilteredLessons(filter, filter2);
            };
            return View(plm);
         }

View

I'm trying to get the @Model.Person.PersonId in here somewhere, without showing it to the user. I thought about putting it in the Filter button all the way at the bottom, but this caused an error

@model Taijitan.Models.ViewModels.PersonLessonModel

<a asp-controller="Lesson" asp-action="Index">Previous</a>
<br />
<form action="/Lesson/LessonsForMember/" method="post">
    <div class="form-inline">
        <select id="Difficulties" name="filter" asp-items="@Model.Difficulties as List<SelectListItem>" class="form-control">
            <option value="">-- All Difficulties --</option>
        </select>

        <select id="Types" name="filter2" asp-items="@Model.Types as List<SelectListItem>" class="form-control">
            <option value="">-- All Types --</option>
        </select>
        //This causes an error
        <button name="id" value="@Model.Person.PersonId" type="submit">Filter</button>
    </div>
</form>

Upvotes: 1

Views: 1526

Answers (1)

Hooman Bahreini
Hooman Bahreini

Reputation: 15559

You can add PersonId as a hidden input field to the form, and it would be posted to the controller.

So you need to include this at the bottom of your form (make sure it is inside the form):

@Html.HiddenFor(m => m.Person.PersonId)

Upvotes: 2

Related Questions