Post with MVC 2, including values outside of form - asp.net-mvc-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

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.

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.

Related

MVC form not submitting to correct action

I have a simple partial with a form inside which is used as a search bar.
#using (Html.BeginForm("Details", "Projects", FormMethod.Get))
{
<div class="row" style="margin-bottom: 20px;">
<div class="col-lg-3 pull-right">
<input type="search" class="form-control" placeholder="Search Code" id="projectSearch" name="code" />
</div>
</div>
}
This should post to my Projects Controller Details Action, however this isn't happening, and I believe this because of the [Route] attribute that is applied to the action, as when I comment this out, the form posts correctly. However I want to use the [Route] attribute.
The action looks like this:
[HttpGet]
[Route("{code}/Details")]
public ActionResult Details(string code)
{
if (code == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
...
return View(viewModel);
}
When the attribute is in use the form will post to this url:
/Projects/Details?code=PP61
which doesn't map to the correct action. Instead I get a resource cannot be found error.
The expected/desired url should look like
/Projects/PP61/Details
This works fine if I create a Url.Action or browse to the URL, so I know this action works, however it doesn't work with a form post. Any ideas why?
Thanks.
Change [HttpGet] to [HttpPost] on the controller and FormMethod.Get to FormMethod.Post in the view.
I have one solution to the problem, it doesn't however answer why this wasn't working in the first place. I have created a separate action which is for the search bar to POST to, this action then redirects to the GET action which I was trying to reach in the first place.
[HttpPost]
public ActionResult ProjectSearch(string code)
{
if (code != "")
{
return RedirectToAction("Details", new { code });
}
else
{
return RedirectToAction("Index");
}
}
This now works correctly, but I would still love to know why this didn't work to begin with if any body has any ideas. Cheers.

Call a function after a form is submitted using jquery

I'm trying to call a function after any form with the class shown below is submitted. However, this doesn't seem to be working for me (the form submits, but the submit button remains active and the loading image is not shown).
$(document).ready(function() {
$('.uniForm').submit(function() {
$('#loadingImage').show();
$(':submit',this).attr('disabled','disabled');
return true;
});
});
Here's some HTML:
<form class="uniForm" id="formABC">
//...form.... here
</form>
<img src="loadimage.gif" style="display: none;" id="loadingImage">
does anyone see anything inherently wrong with this that would be preventing things from working correctly?
I have a feeling it's just not being called correctly. Can I call it myself via some HTML like this?
<button type="button" class="primaryAction" alt="Submit Form" onclick="$('#formABC').submit();">Submit Form</button>
Following your comment, it seems the binding of the handler function to the submit event might be taking place before the form element has been loaded into the DOM.
Ideally, you should bind event handlers only after the DOM has finished loading.
For example:
$(document).ready(function() {
$('.uniForm').submit(function() {
...
});
});
Put an id on the submit input/button and try this:
$('#mySubmitButton').click(function(e) {
e.preventDefault();
e.stopPropagation();
$(this).attr('disabled','disabled');
$('#loadingImage').show(function() {
$(this.form).submit();
});
});
There is a jQuery plugin named jQuery Form Plugin which helps to submit your form from ajax without refresh and then you can do the rest of actions on its success (which occurs exactly after successful form submission):
jQuery(document).ready(function () {
jQuery('#my_submit_button').click(function (e) {
jQuery(this.form).ajaxSubmit({
target: false,
success: function ()
{
your_other_stuff();
},
});
});
});
function your_other_stuff(){
// rest of things
}
Try something else:
$('.uniForm input[type=submit]').click(function(){
$('.uniForm').submit();
//doStuffafterSubmit
});

MVC- receive selected Dropdownlist value in [HttpPost] method on change event

Hey..
How to receive selected Dropdownlist value in [HttpPost] method on change event? I always receive it in [HttpGet] method.
<%: Html.DropDownListFor(model => model.TipTpa, ViewData[ArtikliKonstante.vdListaTipovaTPa] as IEnumerable<SelectListItem>,
new { onchange = "location.href='/Artikli/PromjenaTipa? p='+this.value"})%>
If I declare my method as [HttpPost] I get error, that action doesn't exist. Any idea?
Thx
You need to POST if you want the proper action to be invoked. In your case you are simply redirecting (window.location.href) which sends a GET request.
So you could place the dropdown inside a form and use javascript to submit the form when the selection changes:
<% using (Html.BeginForm("PromjenaTipa", "Artikli", FormMethod.Post, new { id = "myform" })) { %>
<%: Html.DropDownListFor(
model => model.TipTpa,
ViewData[ArtikliKonstante.vdListaTipovaTPa] as IEnumerable<SelectListItem>,
new { id = "tipTpa" }
) %>
<% } %>
and then subscribe for the change event in javascript (example with jquery):
$(function() {
$('tipTpa').change(function() {
$('#myform').submit();
});
});
This will POST the form to the PromjenaTipa action where you could read the selected value:
[HttpPost]
public ActionResult PromjenaTipa(string tipTpa)
{
// tipTpa should contain the selected value
...
}
Another possibility would be to send an AJAX query in the change event. In this case you don't need a form as you could send POST request with AJAX.

Problem posted data with jQuery submit()

I have the script below. I am trying to POST the data and insert it into a database, the jQuery executes just fine, but does not post anything, the action is working properly because when i post the data without the script, the data posts fine and is inserted into the database fine without any errors, so it seems as if the jquery function is posting nothing. can someone please help?
$('#form').live('submit',function(){
$('#form').fadeOut('slow');
$('#div').append("<h2>submittes</h2>");
return false;
});
<form id="form" method="post" action="execute.php" name="form">
<textarea id="text" name="update"></textarea>
<br>
<input type="submit" value="update" id="update-submit">
</form>
EDIT:
$('#form').live('submit',function(){
var updateTextArea = $('#textarea').val();
$.ajax({
type: "POST",
url: "execute.php",
data: updateTextArea,
success: function() {
$('#form').fadeOut('slow');
$('#div').append("<h2>updated</h2>");
}
});
return false;
});
this is what i have for the ajax, but i am still not having any success.
You don't have any AJAX calls in your javascript. You're just fading out the form, appending an h2, and preventing the default action from occurring (which would be to submit the form normally).
Here's a basic example of how to create a POST ajax request:
$('#form').submit(function(){
$.post($(this).attr('action'), { update: $(this).find('#text).val() }, function(){
// success
});
});
Checkout the jQuery API/Docs for more info on this. There are also dozens of tutorials lurking around the net on how to do this.
Well, by returning false from the event handler function, you trigger two things:
prevent the default action (.preventDefault())
stop the event propagation (.stopPropagation())
This prevents that the submit ever happens.
You need to transfer the data on your own within the submit event handler. For instance, create an ajax request which serializes the form data and sends it to your server.
Could look like:
$('#form').live('submit',function(){
$('#form').fadeOut('slow');
$('#div').append("<h2>submittes</h2>");
$.post('execute.php', $(this).serialize(), function(data) {
// do something after success
});
return false;
});

Submit PartialView

I have a masterpage that render's the following PartialView:
<% Html.RenderPartial("AddPage); %>
AddPage Controller looks like this:
public class PagController : Controller
{
[HttpGet]
public PartialViewResult AddPage()
{
return PartialView();
}
[HttpPost]
public PartialViewResult AddPage(FormCollection forms)
{
//some logic here
// some view data here
return PartialView();
}
}
And the view looks like this:
<% using (Html.BeginForm("AddPage", "Page", FormMethod.Post, new { ID = "PageManager" })){%>
<%= Html.TextBox("txtAddPage") %>
<input type="submit" value="AddPage" />
<%} %>
My issue is, that when i hit submit i get redirect to : http://localhost:1234/Page/AddPage, when instead i just want the partialview to be submitted, and return some basic view data if needed, as well as stay on the same page.
Am i having a blonde moment here? cause i know i have done this before
EDIT - This partial view is rendered in multiple pages, not just one.
Fullpage postback solution
This is a bit tricky since you have to know where to go back. I suggest you change your view and add two additional hidden fields (or one and parse its value - as you wish) and store current controller/action values in it.
You can then use this data in POST action to return a RedirectResult like:
return RedirectToAction("action_from_field", "controller_from_field");
Ajax postback solution
You can always submit your data using Ajax in which case your postback URL can be anything you want. In your case it should be to the current page URL. Edit: And Ajax would be the preferred solution in your particular case.
If you want to submit and only reload part of your page, you'll need to use AJAX. The most basic way to do this would be to render the partial view in an UpdatePanel.