0

I am having trouble passing a variable from a html form to a controller within my .NET core project. The variable I am passing to the controller is then used in an interface method call.

My data model for the form:

public class JourneyFormModel
{
    public string fromStationCode { get; set; }
}

my form:

@model SplitTrainTicket.Models.JourneyFormModel

@using (Html.BeginForm("JounreyDetails", "Home", FormMethod.Post))
{
<div class="form-horizontal col-md-6">

    <div class="autocomplete">
        @Html.EditorFor(model => model.fromStationCode, new { htmlAttributes = new { @class = "autocomplete", id = "departStationPicker", @placeholder = "Departing From" } })
    </div>
}

And my controller:

 [HttpPost]

 public IActionResult GetResults(JourneyFormModel form)
    {
        return Ok(_repository.GetAllResults(form.fromStationCode));
    }

    

It seems that the value is null when form.toStationCode is passed to my GetAllResultsMethod. I have tired this with manually with a string and it seems to work fine. Just seems to be an issue getting the string from the form field.

This is also my interface if it is any help:

public interface IJourneyDetailsRepository
{
    List<JourneyModel> GetAllResults(string fromStation);
}

Thanks in advance for anybody who reads this :)

9
  • Couple questions: 1) It seems like fromStationCode is a primary key and identity from a table, and you're putting it out there to let users change it? 2) Your form posts back to home controller jounreyDetails method but your controller example shows a different one. 3) Your controller example doesn't have [HttpPost] annotation so it's a GET method. Your form and the controller don't talk to each other. Commented Jul 7, 2020 at 17:28
  • My bad, I have made edits Commented Jul 7, 2020 at 17:32
  • Still no luck when changing the controller annotation to HttpPost Commented Jul 7, 2020 at 17:37
  • Please read my question #2. Your form is posting back /home/jounreyDetails but your controller (well I don't know the name of the controller) only has GetResults method. Your form is not talking to your controller. Commented Jul 7, 2020 at 17:41
  • 1
    I see. I will spend some time on this. Thank you for pointing me in the right direction Commented Jul 7, 2020 at 18:08

1 Answer 1

1

Just seems to be an issue getting the string from the form field.

The action name in the Html.BeginForm is JounreyDetails, while you want to post the form to GetResults action, you need to change it.

@using (Html.BeginForm("GetResults", "Home", FormMethod.Post))
Sign up to request clarification or add additional context in comments.

Comments

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.