4

In an MVC3 project, i use an Html.BeginForm to post some (model-)values. Along with those i want to send an extra parameter that is not part of the form (the model) but in the ViewBag. Now, when i use a Button (code in answer here: MVC3 razor Error in creating HtmlButtonExtension), all the form values are posted but the extra parameter remains null. When i use an ActionLink, the parameter is posted but the form values are not :) Any know how i can combine the two? Thanks!

@Html.Button("Generate!", new { id = ViewBag.ProjectID })
@Html.ActionLink("Generate!", "Post", new { id = @ViewBag.ProjectID })
Community
  • 1
  • 1
stefjnl
  • 732
  • 3
  • 14
  • 31
  • I haven't tried using ViewBag to return extra data to the action so i don't know but you can use to store extra values and retrieve them using their name from your action –  May 31 '12 at 08:04
  • yes, input type="hidden" is always an option but i was hoping to be able to do it in a more MVC-like way :) – stefjnl May 31 '12 at 09:03

2 Answers2

2

My advice would be to declare a new Object in your App.Domain.Model something like this

namespace App.Domain.Model
{
    public class CustomEntity
    {
        public Project projectEntity { get; set; }
        public int variableUsed { get; set; }
    }
}


In your view you can acces them easily by using CustomEntity.projectEntity and CustomEntity.variableUsed.

Hope it helps

Mihai Labo
  • 1,082
  • 2
  • 16
  • 40
  • i think this is indeed the quickest and cleanest way. ive declared and extra (static!) model class to pass the value. its strange tho that i cant seem to send it as an anonymous type with the button... thanks! – stefjnl May 31 '12 at 09:01
  • yup .. forgot to add the static feature. I've used viewbag for a long time ; this is cleaner and easier to use. Dont forget to mark this as answered. – Mihai Labo May 31 '12 at 09:05
0

You can do something like below.

View code

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @id = "frmId", @name = "frmId" }))
{
        @*You have to define input as a type button not as a sumit. you also need to define hidden variable for the extra value.*@
        <input type="hidden"  name="hndExtraParameter" id="hndExtraParameter" />
        <input value="Submit" type="button" id="btnSubmit" onclick="UpdateHiddenValue()" />
}

<script type="text/javascript">

function ValidateUser() {
$("#hndExtraParameter").val('Assignvaluehere');
$("#frmId").submit();
}

</script>

Controller Code

[HttpPost]
public ActionResult ActionName(Model model, string hndExtraParameter)
{
//Do your operation here.
}
alok_dida
  • 1,723
  • 2
  • 17
  • 36
  • yes, input type="hidden" is always an option but i was hoping to be able to do it in a more MVC-like way :) – stefjnl May 31 '12 at 09:03