How to call a Controller from a PartialView in MVC3 - c#

I have a PartialView which I need to create a button on, and once a user clicks on this button, it must send a HTTPGET to a controller that receives the model. How do I call the HTTPGET action from the PartialView?
Any idea as to how to do this in MVC3?

may be this solution work :
<form method="get" action="controllerName" enctype="multipart/form-data">
#html.partial("viewName")
<input type="submit" value="Send" ... />
</form>

There are a few ways that you can achieve this. The easiest way is to use an ajax request to send the data back to the controller using jQuery (http://api.jquery.com/jQuery.get/). However I would not use a HTTP GET for this. Although not enforced it is best to stick to using the HTTP verbs in the way that they were intended ie GET is for receiving data, POST is for sending data to the server.

use this to create the form in your partial view,
#{using (Html.BeginForm("Create", "Person", FormMethod.Get, new {
enctype = "multipart/form-data",
id = "<id of the form>" }))
{
//body of your form
}
Here you can see that, type of the form method has been passed in to the Html.BeginForm method as "FormMethod.Get". If you want to sent the response to a Post method, uset "FormMethod.Post".

Related

Taking non-model information from a text box and passing it through a Actionlink

So I am trying to set up a website that has questions, answers, and comments, much like stackoverflow. right now, I am trying to get comments to work correctly. I have decided that I will try to use an ActionLink to send the comment text to the controller. Is there any way that you can do this without invoking the model fields?
Use a simple form submit, then grab your submitted data via a FormCollection
[HttpPost]
public ActionResult SubmitComment(FormCollection collection)
{
string comment = collection["comment"];
}
and for your view
#using (Html.BeginForm("SubmitComment", "CommentsController"))
{
#Html.TextBox("comment")
<input type="submit" value="submit" />
}
In my opninon you are better off binding this data to a model in the long run. See this link for more details : Is there any good reason to use FormCollection instead of ViewModel?
What if you place your inputs to <form> tag ?
#using (Html.BeginForm("AddComent", "CommentsController"))
{
#Html.TextBox("comment")
<input type="submit" value="Post Your Comment" />
}
P.S.
Other option (that i prefer) would be to send Ajax Post calls with JQuery: $.post("#Url.Action("$Action", "$Controller")", { $parameter: $data });

Basic MVC (button to send e-mail) - ActionLink?

I have a 'mail server configuration' kind of view. On this view are 2 buttons:
[SOME FORM FIELDS]
<input class="button" type="submit" value="#T("Save")" />
<input class="button" type="submit" value="#T("Send Test Email")" />
The first button calls off to my controller and returns the same view with any validation/success messages (this is a form):
[HttpPost]
public ActionResult Index(MailServerSettingsViewModel viewModel)
{
...
That works brilliantly, but obviously the 'Send Test Email' button will do the same.
Assuming I don't want to come away from the page (i.e. load a different view), but want to call off to another controller to send a test e-mail, is the 'proper' way to do this to use the ActionLink helper? From this other controller can I then return this same form view? Or can I somehow use the same controller but determine which button was pressed to decide whether to validate the view model or just call off to another service/class/whatever to send the test e-mail and responding appropriately?
You can probably tell from the way I'm asking this that I come from a WebForms background and it's still a case of me getting used to what's what with MVC.
What I've Tried
For now, I'm actually calling off to this other controller asynchronously with AJAX. It actually works well, and is probably most appropriate, but this won't always be the case so I want to know how I'd achieve the above for other scenarios.
If you don't want ajax you can start a thread to send the email in your controller.
#Html.ActionLink("Send Test Email",
"actionName", "ControllerName",
new { MailServerSettingsViewModel }, new { #class = "button" })
If you set the 'name' attribute on both submit buttons to the same value, you can detect which was clicked in your controller by inspecting the value.

Event when form submittion ends

I have this:
<form id="import_form" method="post" enctype="multipart/form-data" action="/Blah/Blah">
<input type="file" id="fileUpload" name="fileUpload"/>
<input type="submit" name="submit" value="Import"/>
</form>
$('#import_form').submit(function () {
...
});
Here is the c# method:
[AcceptVerbs(HttpVerbs.Post)]
public string Blah(HttpPostedFileBase fileUpload, FormCollection form)
{ ... }
I want when Blah finishes executing a javacript code to start executing. How to do this?
The submit event is called before it.
This depends on how the form is being submitted.
If you're submitting the form via AJAX then you can execute some JavaScript in the handler for the response. However, given that there's a submit button, I'm assuming for the moment that you're not doing this via AJAX and are instead posting the whole page to the server and rendering a response.
In this case, to execute some JavaScript after the form post, you're going to need to render that JavaScript in the response from the server as part of the next page. When the server constructs the view, include the JavaScript you want to execute in that view.
Keep in mind the request/response nature of the web. When something on the server executes, the client is unaware of it and disconnected from it. The end result of any server-side processing should be an HTTP response to the client. In the event of submitting a form or clicking a link or anything which results in a page reload, that response is in the form of a new page (view). So anything that you want to do on the client after the server-side processing needs to happen as part of that response.
Edit: I just noticed that Blah is returning a string. Is this even working for you? How does the form submit result in a new view? Or am I unaware of a feature in ASP.NET MVC?
This is what I did in the end.
My form returns the exact same view with whom it was called.
I add a ViewData in the Blah method.
In the view, in the $(function()) event I check if ViewData has a value, I execute the javascript code.

MVC: what code gets called when you click the "submit" button?

MVC newbie question; I'm learning by playing around rather than Reading The Manual... :)
I see when I create an "Edit" view that the auto-generated view includes a "submit" button:
<input type="submit" value="Save" />
But what code gets called behind the scenes to do this save? Specifically, the model underlying this view has its own fancy save logic in code that I would want to call. How do I get the view to invoke my code instead of whatever standard code is being called invisibly behind the scenes?
It's not the button that defines what happens, but the form itself. The button of type submit (one per form) just triggers the form submission, which is handled by the form itself.
A form has an action - e.g.:
<form name="input" action="users/save" method="post">
<!-- Form content goes here -->
<input type="submit" value="Submit" />
</form>
The action is an URL and what happens is that the browser collects the values of all the fields in the form (<input...>) and posts them to the specified url.
In ASP.NET MVC forms are usually defined using the Html helpers, so that building the URL for the form action is delegated to ASP.NET MVC. For the above for example:
<% using(Html.BeginForm("Save", "Users")) %>
<% { %>
<!-- Form content goes here -->
<input type="submit" value="Save" />
<% } %>
Which in this case will create a url /users/save and the form will post to that url. That in terms will trigger the ASP.NET routing which will handle the /users/save url and break it into chunks so that it knows that it has to invoke the "Save" action method on the "Users" controller class. It will then read all the incoming field name-value pairs and try to map them to the method parameter names if any.
It would call whatever public action method the form action is pointing to on your controller. You can then call save on the view model.
public virtual ActionResult Save(MyViewModel model) {
model.Save();
--- more code to do stuff here
}
Set your form action to MyController/Save
You can also use using (Html.BeginForm... in your code to point the form to a specific action method on a specific controller.
when you click submit button, request goes to the HTTp Module which directs it to corresponding controller action. when edit view is created from template the post address of the form is same as of the edit form i.e if you are visiting /home/edit you can see following html in form's opening tag
<form method="post" action="/home/edit">
you can have another action method that only accepts post requests like
[HttpPost]
public ActionResult Edit(int id, ViewModel model)
{
//put your logic here handling submitted values
}
HttpPost attribute tells that it will only handle post request as opposed to get requested used to render the form
it calls the Action method defined in the action part of the form element
eg:
<form action="/Account/LogOn" id="loginForm" method="post">
The LogOn action in the Account controller will be invoked in this form
The ViewPage has a BeginForm Method using (Html.BeginForm() at the top which would render the FormTag. This method has a overload which takes ActionName and controller Name. So you can specify the action in your controller which has to be called.

MVC 2 Ajax.Beginform passes returned Html + Json to javascript function

I have a small partial Create Person form in a page above a table of results. I want to be able to post the form to the server, which I can do no problem with ajax.Beginform.
<% using (Ajax.BeginForm("Create", new AjaxOptions { OnComplete = "ProcessResponse" }))
{%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%=Html.LabelFor(model => model.FirstName)%>
</div>
<div class="editor-field">
<%=Html.TextBoxFor(model => model.FirstName)%>
<%=Html.ValidationMessageFor(model => model.FirstName)%>
</div>
<div class="editor-label">
<%=Html.LabelFor(model => model.LastName)%>
</div>
<div class="editor-field">
<%=Html.TextBoxFor(model => model.LastName)%>
<%=Html.ValidationMessageFor(model => model.LastName)%>
</div>
<p>
<input type="submit" />
</p>
</fieldset>
<%
}
%>
Then in my controller I want to be able to post back a partial which is just a table row
if the create is successful and append it to the table, which I can do easily with jquery.
$('#personTable tr:last').after(data);
However, if server validation fails I want to pass back my partial create person form with the validation errors and replace the existing Create Person form.
I have tried returning a Json array
Controller:
return Json(new
{
Success = true,
Html= this.RenderViewToString("PersonSubform",person)
});
Javascript:
var json_data = response.get_response().get_object();
with a pass/fail flag and the partial rendered as a string using the solition below but that doesnt render the mvc validation controls when the form fails.
SO RenderPartialToString
So, is there any way I can hand my javascript the out of the box PartialView("PersonForm") as its returned from my ajax.form? Can I pass some addition info as a Json array so I can tell if its pass or fail and maybe add a message?
UPDATE
I can now pass the HTML of a PartialView to my javascript but I need to pass some additional data pairs like ServerValidation : true/false and ActionMessage : "you have just created a Person Bill". Ideally I would pass a Json array rather than hidden fields in my partial.
function ProcessResponse(response) {
var html = response.get_data();
$("#campaignSubform").html(html);
}
Many thanks in advance
what I've done in this circumstance is actually render out a partial view that has all the information (e.g. validation info, etc) and then use DOM functions in jquery to extract what I need, if it's more than just for display. Keeps everything in one format that way and I don't have to wory about handling both json and html.
Why do you even need to pass back the partial person object? As far as I'm aware ASP.NET MVC should leave the form filled out as the user filled it in but add validation errors to the form.
They can then correct the errors and submit the form again. Sound more like a problem with the design of the web site and something that you shouldn't be doing in the first place.
If you need to store the data the user entered I would create a json person object and submit this object with the ajax request and then when the validation errors come back you already have the data that was sent.
Ajax enables you to have state in the web client as long as the user is viewing the page.

Categories