asp.net MVC Handle Partial Postback Response - asp.net-mvc

I have multiple pages containing the same partial view. The partial contains a form that posts to an action. After a post I want to return to the page I was on before the post. What's the best way to do this?
Example:
Partial View:
form post action = note/create/
Pages
page1:
products/index/
page2:
customer/details/
page3:
order/details/
These 3 pages contain the partial view, when posting the partial it redirects to note/create/. I need to return to the original page on success.
Thanks
Simon

Either have the post happen via AJAX -- thus not leaving the page, or pass the current controller/action/id (or the Url as a whole) as parameters to the action that handles the post. See below for an example of the later.
<% using (Html.BeginForm(...)) { %>
<input type='hidden'
name='currentController'
value='<%= ViewContext.RouteData["controller"] %>' />
<input type='hidden'
name='currentAction'
value='<%= ViewContext.RouteData["action"] %>' />
<input type='hidden'
name='<%= ViewContext.RouteData["id"] %>' />
...rest of form...
<% } %>
or
<% using (Html.BeginForm( ...,
new { ReturnUrl = Url.Action( ViewContext.RouteData["action"],
ViewContext.RouteData ) }, ... )) { %>
....
<% } %>

You can store the current page address in a hidden field and send it with Post request.
In your partial view:
<script type="text/javascript">
var field = document.getElementById("currentPage");
field.value=document.location.href;
</script>
<form method="post" action="note/create/">
...
<input type="hidden" value="" id="currentPage" name="currentPage" />
</form>
Then retrieve the address of the hidden input and redirect the user to it.

Related

Form reloads the page but does not submit

I'm working on Asp.net MVC Application. When I use a form and try to submit , it just reloads the page. I have included the method and Action info , but the form and data are not sent to address specified in action attribute of form. Any help please
<form action="/Search/SearchforQuery/" method="post" runat="server">
<p>Search : <input style="font-size:medium; width: 600px; height: 29px;"
name="searchField" id="searchField" /></p>
</div> <input type="submit" value="Submit Form" />
</form>
Why are you using runat="server" if you are using MVC?
Delete it.
Try to use:
#{ using (Html.BeginForm(...))
{
<p>
Content here
</p>
}

asp.net mvc posting form values using html.actionlink

how can i post the form values using html.actionlink, don't want to use routes dictionary
<%=Html.ActionLink("Download", "MyFiles", "Jobs", null, new { #class = "cvclick" })%>
A link points to an HTTP GET request.
An HTTP GET request is sent to a URL; the URL must be defined using a route.
To POST values you could use an HTML form:
<% using (Html.BeginForm("MyFiles", "Jobs")) { %>
<%= Html.Hidden("key1", "value1") %>
<%= Html.Hidden("key2", "value2") %>
<input type="submit" value="Download" />
<% } %>
To POST values you could use Spark View Engine and a HTML form:
<form action="myfiles" controller="jobs">
<hidden name="key1" value="value1" />
<hidden name="key2" value="value2" />
<submit title="Download" />
</form>
(The code uses some pretty standard bindings that be wired in Spark)
As for links and ActionLink. I would use the ajax helper instead since it can POST stuff. (Ajax.ActionLink)
Edit
So you want to DOWNLOAD a file? Well. The link should point on an action in your controller. The action should return a FileResult with your file. See here: http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.file(v=vs.90).aspx
You can post the data using :-
anthing inside Beginform will be posted
<% using (Html.BeginForm("ActionName", "ControllerName"))
{ %>
texbox code
<input type="submit" class="dASButton" value="Submit" />
<% } %>

asp mvc user controls

I want to write user control to sending email.
I write that control:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<form action="" method="post">
<div class="box">
<div class="box-header">
Rejestracja</div>
<div class="box-content">
<div>
Imię
</div>
<div>
<input name="firstname" type="text" />
</div>
<div>
Nazwisko
</div>
<div>
<input name="lastname" type="text" />
</div>
<div>
Email
</div>
<div>
<input name="email" type="text" />
</div>
<div>
Ulica nr domu mieszkania
</div>
<div>
<input name="street" type="text" />
</div>
</div>
<div class="box-info">
Wypełnij formularz rejestracyjny i dołącz do klubu Oriflame.
</div>
</div>
<div style="clear: both;">
</div>
</form>
And i put this control in masterpage:
<% Html.RenderPartial("Kontakt"); %>
That control named :kontakt.aspx" and it is in shared folder
My question is where i must write code with sending email. What action i myst set in controls form.
This control was be on all sites.
Regards
The form needs to post to a URL that is setup to route to a controller action. That could be the current page's Url or a different Url.
In your controller you want a method that accepts the form fields. This could be a FormCollection object or a strongly typed model who's properties map to the form names.
[HttpPost]
public ActionResult Foo(FormCollection form)
{
.. use the form collection to construct your email ...
}
If you're using a strongly typed view, rather than building the HTML inputs yourself you could do:
<%= Html.TextBoxFor(x => x.FirstName) %>
And in your controller action you can use the model rather than the FormCollection:
[HttpPost]
public ActionResult Foo(KontaktModel details)
{
.. use the details object to construct your email ...
}
I suggest taking a look through the tutorials at http://asp.net/mvc as well as doing the NerdDinner tutorial.
You have to create some sort of Controller that will receive form data. And you can send those emails from the server (from controller or whatever you chose to send it).
Write your email creation and sending code in a controller method. You'd then call it from this Kontakt partial view like this:
<% using (Html.BeginForm("SendMail", "Mail")) { %>
Where SendMail is the method, and Mail is the name of the controller.
public ActionResult SendMail()
{
//build your mail objects and send as needed.
return View();
}

ASP.NET MVC Create querystring from form

I am trying to create a simple search box that results in something like http://www.example.com/Search?s=searchTerm I have the routing setup so that it accepts a url like this, and does the right thing. The problem I'm having is getting the form to create the querystring. I have tried many variations of:
<% using (Html.BeginForm("Search", "Home", FormMethod.Get, new { ???? })) {%>
<input id="submitSearch" class="searchBox" type="text" runat="server"/>
<input type="submit" value="Search" /> <%} %>
I'm not sure how to setup the Html.BeginForm so it grabs the submitSearch value and passes it to /Search?s=valueHere. This seems like I am missing something easy.
You need to set name on the input box to s.
<% using (Html.BeginForm("Search", "Home", FormMethod.Get, new { })) { %>
<input id="s" name="s" class="searchBox" type="text" />
<input type="submit" value="Search" />
<% } %>
Also, note that I changed the id to s as well, since common practice is to have the same value for name and id. However, it is only the name attribute that affects the query string name in the request.
And as David noted in a comment, the runat="server" is not needed in ASP.NET MVC.

How to dispatch on the result of submiting an AJAX form in ASP.Net MVC?

In ASP.Net MVC, having a form more or less like this:
<% using (Ajax.BeginForm(new AjaxOptions() { OnSuccess="onSuccess"})) {%>
<p>
<label for="Comment">Comment:</label>
<%= Html.TextArea("Comment")%>
<%= Html.ValidationMessage("Comment", "*")%>
</p>
<p><input type="submit" value="Submit comment" /></p>
<% } %>
How can the onSuccess Javascript function know whether the result is another version of the form because it didn't validate, a comment as a div to add to the list of comments or a log in page that should be pop up for logging in?
You can define that in your returning JSON or whatever transport method you use?
Not sure if that's what you're looking for, but also: this is how the onSuccess function is called:
YourFunction(ajaxContext);
AjaxContext is defined as follows:
AjaxContext ajaxContext = new AjaxContext(request, updateElement, loadingElement, ajaxOptions.InsertionMode);
You should replace the code inside your ajax form with a new partial view, then you will return that partial view from your controller. The partial view would consist in:
<p>
<label for="Comment">Comment:</label>
<%= Html.TextArea("Comment")%>
<%= Html.ValidationMessage("Comment", "*")%>
</p>
<p><input type="submit" value="Submit comment" /></p>
This way, your partial view works just like a regular view.
Unfortunately there is no simple way to execute javascript as a response (since you are responding with a view). It would be easier if your response was a Json string, but in that case, you can't use the AjaxForm because the Json string would be rendered on screen as a result of submitting the form (and processing its response). This may work though (I haven't tried it):
<p>
<label for="Comment">Comment:</label>
<%= Html.TextArea("Comment")%>
<%= Html.ValidationMessage("Comment", "*")%>
</p>
<p><input type="submit" value="Submit comment" /></p>
<script type="text/javascript">
function processResponse(data){
// blah blah blah
}
processResponse(<%= ViewData["dataFromTheController"] %>);
</script>
Your could simply add different CSS classes to the root elements of your responses (for example .form, .comments, .login). And then (for example in jQuery):
var response = $(responseContent);
$('.form', response).each(function() {
// $(this) is form
});
$('.comments', response).each(function() {
// $(this) is comments
});
$('.login', response).each(function() {
// $(this) is login page
});
How can the onSuccess Javascript
function know whether the result is
another version of the form because it
didn't validate, a comment as a div to
add to the list of comments or a log
in page that should be pop up for
logging in?
The short answer is that it cannot unless you explicitly validate it. That's because JSON is transported as a string and when the client side Javascript gets the string.
For starters you should implicitly know what sort of object to expect. If you are calling an web service # Cars/List then you know the returned object will be a list of cars and you parse that appropriately in your client. You can run into errors which you should handle appropriately by retrying the request or logging them or showing an error message.
I would recommend you to use the jquery.form plugin, with this you can have a normal form to act like an ajax one, like this:
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>

Resources