0

View:

@using (Html.BeginForm("UpdateMaterial", "MyController", FormMethod.Post, Model.MaterialId))
    {
    @Html.AntiForgeryToken()
    <input type="submit" class="btn btn-primary custom" value="Derivate Material" />
    }

Controller:

[HttpPost]
public ActionResult UpdateMaterial(int? matId)
        {
            if (matId == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
        //do something here
        }

The Id I send its always null. How do i change this?

1 Answer 1

1

Your Model.MaterialId should be a form element:

@using (Html.BeginForm("UpdateMaterial", "MyController", FormMethod.Post))
{
     @Html.HiddenFor(model => model.MaterialId)

     @Html.AntiForgeryToken()
     <input type="submit" class="btn btn-primary custom" value="Derivate Material" />
}

Additionally, you should change your action definition and make it accept the type of your model, instead of a int?:

[HttpPost]
public ActionResult UpdateMaterial(MyModelType model)
{
     if (model.matId == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     //do something here
}
Sign up to request clarification or add additional context in comments.

4 Comments

@Html.EditorFor places an input text in the View. I want to be able to automatically send the Id to the Controller. I'm in the "Detail" View of a specific Material and I already know the MaterialId because of the model.
@Aoren, you need a hidden input for that. I updated my answer.
Q: I'm sending an object of (in the case of your answer) "MyModelType" with all the specs from the Material in the View or is it just an integer?
@Aoren it really depends on what you're trying to accomplish. If you just need to send a single id, you'd be better of with AJAX or even an action link. If you want to use a form, then posting a model would be appropriate.

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.