kjosh
kjosh

Reputation: 133

Return FilePathResult and ViewResult in MVC HttpPost action controller

The View accepts some user input and has a "Download" button that lets users download an xml generated based on the entered fields. I also have the [Required] attribute validation in the model that displays the Error message as expected

[Required(ErrorMessage="Provider is Required")]
string provider { get; set; }

When the user fills out the missed mandatory field and hits "Download" the controller returns the xml as a FilePathResult

[AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult TestXMLCreator(TemplateModel model)
        {
        .
        .
        if (ModelState.IsValid)
            {
            .
            .
            System.IO.File.WriteAllText(Server.MapPath("~/Generated.xml"), testXml);
            return File(Server.MapPath("~/Generated.xml"), "text/plain", testXML.xml");
            }
        return View(model)

When the ModelState in valid and the File is returned as a result, the view is not refreshed and the old validation errors are still displayed. How can a FileResult be returned and the View refreshed as well?

Upvotes: 0

Views: 1297

Answers (1)

JotaBe
JotaBe

Reputation: 39014

You cannot do the two things in a single operation.

The only thing that you can do is to return the refreshed view, including a link to the generated file. The user will only have to make and additional click to donwload the file.

If you want to avoid that click, you can simulate it by using JavaScript, for example, with jQuery, like in this SO Q&A.

Upvotes: 1

Related Questions