How to send Form Data from Controller - asp.net-mvc

I am working on this project, where my Application need to connect to a third party application.
My steps
Create form to submit data.
Get Form data in MY controller Action. Save mine required variables to database.
Then send the data to Third Party Application.
Now the problem here is that, i need to send the data as Submit Form.
The Third party app takes the values as
Request.form("FormVal")
I can make no changes to the Third party Application.
So how do i send the Form data through my Controller action to the Third Party application?
Also
return view("action", model); // the model is needed to be sent.
it works for the view in my own Application. However I need to send it to an external view(third party) with the model so they can get value as
Request.form("FormVal")
I see the Redirect commands can go the external view but i cannot send the form Data with it.

You can use HttpClient to send data to the third party application.
like this:
var formValues = new Dictionary<string,string>();
formValues.Add("Key", "Value");
HttpResponseMessage response = await httpClient.PostAsync(thirdPartyUrl, new FormUrlEncodedContent(formValues));
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Edited:
If you are not using .NET Framework 4.5 you can use the WebClient.UploadValues instead.
byte[] responseArray = myWebClient.UploadValues(thirdPartyUrl,myNameValueCollection);

the HttpResponseMessage was not what i actually wanted. I also needed to redirect.
So I used javascript/jquery for this.
I created two views
1st is the user input view.
2nd is the Redirect View
From the 1st view I post to my controller then, call my redirect view from the controller action
return view("redirectView", model);
In the Redirect view I created a form with hidden inputs.
#HiddenFor(m=>m.SomeValue)
Then on page load i used javascript to Submit the form.
$("form#formID").submit();
This works for me right now.
Also thanks to Kambiz for making me understand this issue.

Related

Return view to client from web service

I need to develop a payment gateway web service which can be called from all my other application.I use ASP.net web API for this.
I created an HTTP post service which accepts XML as an input parameter.I will parse this XML.if there is sufficient information it will be redirected to payment page or otherwise it will show a page which collects the sufficient data from user. So it must return a view to user and custom error codes and messages.
These are my needs and I want to know which is the best way to accomplish this.
Can I use web API controller or MVC controller for this?
How will the client show the view returned? Inside iframe is not considered as a good choice for me.Is there any other good ways to show the page?
You can use RazorEngine to parse view in WebApi.
var templatePath = HttpContext.Current.Server.MapPath("~/Views/Payment/Form.cshtml");
var templateContent = File.ReadAllText(templatePath);
var templateString = Razor.Parse(templateContent, new ClassA());
return Ok(new {
ErrorCode = "000",
Html = templateString
});
Your can refer this link https://antaris.github.io/RazorEngine/ for quickstart.

MVC Redirect to a different view in another controller

After a user has completed a form in MVC and the post action is underway, I am trying to redirect them back to another view within another model.
Eg. This form is a sub form of a main form and once the user has complete this sub form I want them to go back to the main form.
I thought the following might have done it, but it doesn't recognize the model...
//send back to edit page of the referral
return RedirectToAction("Edit", clientViewRecord.client);
Any suggestions are more that welcome...
You can't do it the way you are doing it. You are trying to pass a complex object in the url, and that just doesn't work. The best way to do this is using route values, but that requires you to build the route values specifically. Because of all this work, and the fact that the route values will be shown on the URL, you probably want this to be as simple a concise as possible. I suggest only passing the ID to the object, which you would then use to look up the object in the target action method.
For instance:
return RedirectToAction("Edit", new {id = clientViewRecord.client.ClientId});
The above assumes you at using standard MVC routing that takes an id parameter. and that client is a complex object and not just the id, in which case you'd just use id = clientViewRecord.client
A redirect is actually just a simple response. It has a status code (302 or 307 typically) and a Location response header that includes the URL you want to redirect to. Once the client receives this response, they will typically, then, request that URL via GET. Importantly, that's a brand new request, and the client will not include any data with it other than things that typically go along for the ride by default, like cookies.
Long and short, you cannot redirect with a "payload". That's just not how HTTP works. If you need the data after the redirect, you must persist it in some way, whether that be in a database or in the user's session.
If your intending to redirect to an action with the model. I could suggest using the tempdata to pass the model to the action method.
TempData["client"] = clientViewRecord.client;
return RedirectToAction("Edit");
public ActionResult Edit ()
{
if (TempData["client"] != null)
{
var client= TempData["client"] as Client ;
//to do...
}
}

ASP NET MVC partial view rendering without postback request form view to controller?

I am using ASP NET MVC4, I want to use partial view to update my main view. On the server I get certain events from another server, and when that happens I want to update the partial view and post it to the client. How can I do that? In other words, I want a way to force rendering partial view on the server side without a postback request coming from the client. Is that possible, or the client must be informed first and then does its own postback action to trigger the partial view rendering?
Call The follwing Ajax call on every other server event or call it periodically
$.get('#Url.Action("ActionName", "ControllerName")', function (data) {
$('#Id of div where Partial View is renderred').html(data);
});
In the action called.
public ActionResult ActionName()
{
//load your model with changes
return PartialView("Name of your partial view", model);
}
This is a better job for SignalR for large scale Real-time work reference:
[http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server][1]
Or if you just need to stay on single medium, you can look into node.js, which is Server side javascript and allows for binding of js function to server driven events (i.e. Client independent)
One last thought would be to use events and kick out Web Api Responses, but that would be getting a lot of weight on JSON without page requests.

Pass javascript parameter to partial view in asp.net mvc

lets say I want to a partial view like the following sample
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
in the jsparameter I want to pass as a parameter that is the result of a javascript function. Maybe this is not logical because javascript runs on the client, but how can I achieve a similar functionality ? thank you in advance
If you need to call a part of a page based on some actions or values determined by actions on the client side, then you should think to use JavaScript (preferably jQuery) and Ajax.
Through jQuery-Ajax, you could easily call a Partial view through the Contoler and since it's a regular HTTP request, you would be able to pass all the parameters you need.
Using code as :
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
is not possible since it is rendered by the server before it's sent to the client browser.

Work flow for creating and returning PDF in MVC

I'm using microsoft's MVC platform to create a web application. In this application, users will fill out a HTML form, click submit, get redirected to a successful message page and receive a printout in pdf form of the form. In addition, I also want to save their entries in the form in a database. I'm using iTextSharp to create and edit the PDF.
I'm looking for advice on managing the workflow in MVC. Specifically, I have a controller method that would direct the workflow for :
saving the form entries to a database,
creating and editing the PDF,
directing the user to a success page,
returning the PDF for the user to download.
My major question is: how should I delegate the tasks of redirecting to the success page and returning the pdf? As of right now, my controller seems to be able to return only one or the other. Can I redirect to a View that "comes with" a PDF?
What I do in a case like this is create a controller action that returns the PDF associated with a given entry id in the database.
public FileResult DownloadPdf(int id)
{
byte[] data;
// ... Generate PDF
return File(data, "application/pdf");
}
Then the controller action which handles the form POST does the following:
Saving the entry values to the database.
Retrieving the primary key of the saved form entry set.
Redirecting to the success view and passing the primary key to it.
Then the success view can use the id it has been given to either link to the PDF (as a download link) or can embed it in an iframe (yuck!).
Note that this only works because you are saving the values in a database. If don't use a database, you have to either:
Encode all the form data in the query string (which has a limited size)
Store the form data in the Session (which is not recommended)
Hope that helps.

Resources