Post with MVC 2, including values outside of form

自作多情 提交于 2019-12-14 03:10:52

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3820860/post-with-mvc-2-including-values-outside-of-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!