Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing extra data to a post controller - MVC

Let's say I have the model

public class ViewModel 
{
    [Required]
    [Display(Name = "Email address")]
    public string Email { get; set; }

    public string ExtraData{ get; set; }
}

Where ExtraData is simply some extra text that gets added in the GET action:

    [HttpGet] 
    public ActionResult ActionMethod()
    {
        ViewModel modelWithExtraData= new ViewModel{ ExtraData = "Some extra data." };
        return PartialView("MyView", modelWithExtraData);
    }

And gets rendered inside the view as such:

<form>
    @Html.TextBoxFor(m => m.Email)
    <div>@Model.ExtraData</div>
<form>

When this form gets posted the the controller, I'd like the extra data "Some extra data" to be intact and posted with the model but this does not happen.

    [HttpPost]
    public ActionResult ActionMethod(ViewModel model)
    {
        //model.ExtraData = null ... Not good
    }

I looked through all the @Html helper methods but can't seem to find the right one to simply display the text (non-editable) and send it back.

like image 463
parliament Avatar asked May 11 '26 03:05

parliament


1 Answers

You could include the extra data as a hidden field inside the form alongside with the textbox:

<form>
    @Html.TextBoxFor(m => m.Email)
    @Html.HiddenFor(m => m.ExtraData)
    <div>@Model.ExtraData</div>
<form>
like image 123
Darin Dimitrov Avatar answered May 13 '26 20:05

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!