views:

25

answers:

2

I'm pretty new to MVC 2 and I'm having problems figuring out how to post values that lies outside the form.

This is my code very simplified:

<input type="text" id="TextboxOutsideForm"/>    
<% using (Html.BeginForm("Edit", "Home", FormMethod.Post)) {%>
    <%: Html.ValidationSummary(true) %>
      <%: Html.TextBoxFor(model => model.Stuff) %>
         <input type="submit" value="Save" />
<% } %>

TextboxOutsideForm can be changed by the user and when pushing save I want to include the value from this control to the action in the controller. It would also be great if i could use model binding at the same time. This would be great:

[HttpPost]
public ActionResult Edit(int id, Model model, string valueFromTextbox)

Or just a FormCollection and a value.. I know that in this simplified example i could just put the textbox inside of the form, but in real life the control is 3rd party and is creating loads of of other stuff, so i just need to grab the value with jquery maybe and post it..

Is this possible?

Thanks

A: 

If you use a normal form post only inputs inside the form will be sent to the server. To achieve what you are looking for you will need to submit the form using AJAX. Example:

$(function() {
    $('form').submit(function() {
        $.ajax{
            url: this.action,
            type: this.method,
            data: $(this).clone().append($('#TextboxOutsideForm').clone()).serialize(),
            success: function(result) {
                alert('form successfully posted');
            }
        });
        return false;
    });
});

Also don't forget to give a name to the input field which is outside the form.

Darin Dimitrov
Really nice, it worked perfectly! Do you have any idea if there is a way to automatically escape html input when posting this way? The control i'm getting the value from is a rich text box with loads of html in it, so the request can't complete.
Andreas
A: 

you can have a look at this question that explains how to dynamically create the form and submit it. you can hijeck the submit event and add value into form dynamically

$(function() {
    $('form').submit(function() {
        $(this).append($("#ValueOutsideForm"));
        return true;
    });
});

this way u don't have to rely on ajax and u can post ur form synchronously.

Muhammad Adeel Zahid
This also worked excellent, thank you!
Andreas