1

So I have an Ajax form with validation, which works. My problem is my POST Action:

[HttpPost]
public ActionResult AddUpdateConfigs(StorageConfigurationModel modelbind)
{
    if (ModelState.IsValid)
    {
       //blablabla more code
    }
    else
    {
        return PartialView("cbpnlNewUpdateConfigs",modelbind);
    }
}

One of the things I do when the model is valid, is trying to use the values, for example, a UNC path I have, and I need to see if that UNC path exists, so I do:

    try
    {
        DirectoryInfo dir = new DirectoryInfo(modelbind.Location);
        if (dir.Exists)
        {
            //bla bla bla
        }
        else
        {
            return //something I dont know what
        }
    }
    catch (Exception j)
    {
        return //something I dont know what
    }

So I dont know what would be correct to return to match the Action type and also have the proper message in the client side.

Any ideas?

tereško
  • 58,060
  • 25
  • 98
  • 150
AAlferez
  • 1,480
  • 1
  • 22
  • 48

4 Answers4

2

You can add an error to your ModelState:

ModelState.AddModelError(string.Empty, "Path does not exist.");

The key here is to use string.Empty as the key for ModelState.AddModelError.

And then display it in the View:

@Html.ValidationSummary()

This way you can use the same view that you use when your model is not valid (!ModelState.IsValid).

Source: ModelState.AddModelError - How can I add an error that isn't for a property?

Community
  • 1
  • 1
polkduran
  • 2,533
  • 24
  • 34
  • Like your solution, but when I add the data to the DB, then what should I return for saying it was successful? – AAlferez Jun 12 '13 at 14:52
  • I suppose that you are filling some html container element with your response (Partial View) when you have errors. Well you can return a different partial view when everything is OK. – polkduran Jun 12 '13 at 14:58
  • I do, but my onSuccess function is not firing – AAlferez Jun 12 '13 at 14:59
  • Have you checked what kind of response do you get? I mean `200`, `500`. You may need to **debug** on the server side and see if everything is OK. – polkduran Jun 12 '13 at 15:04
0

For the first condition you can use the HttpStatusCode enum and use the NotFound constant.

http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx

For the exception you need to find out exactly what the exception is if you want to use a specific HTTP error response code.

Otherwise you could use InternalServerError to indicate a general server error has occurred.

Hope this helps

Shahbaz

BigBaz
  • 83
  • 4
0

You could return a JsonResult with a Success property and either the Html of the view or an error Message which you can read from your ajax response object:

    [HttpPost]
    public JsonResult AddUpdateConfigs(StorageConfigurationModel modelbind)
    {
        if(!allowed) {
          return Json(new { Success = false, Message = "blah blah blah"}, JsonRequestBehavior.DenyGet);
        }
        else
        {
            return Json( new {Success = true, Html = RenderPartialView("cbpnlNewUpdateConfigs", model)}, JsonRequestBehavior.DenyGet);
        }
    }

    public static class PartialViewHelper
        {
            public static string RenderPartialView(this Controller controller, string viewName, object model)
            {
                if (string.IsNullOrEmpty(viewName))
                    viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

                controller.ViewData.Model = model;
                using (var sw = new StringWriter())
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                    var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                    viewResult.View.Render(viewContext, sw);

                    return sw.GetStringBuilder().ToString();
                }
            }

            public static string RenderView(this Controller controller, string viewName, object model)
            {
                if (string.IsNullOrEmpty(viewName))
                    viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

                controller.ViewData.Model = model;
                using (var sw = new StringWriter())
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, String.Empty);
                    var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                    viewResult.View.Render(viewContext, sw);

                    return sw.GetStringBuilder().ToString();
                }
            }
        }
jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
0

Since it is an ajax call ,You may send a response in the JSON format.

if(someConditionTrue)
{
  //Make changes to DB 
  return Json(new { Status="Success"});
}
else
{
 return Json(new { Status="Error", Message="Directory not found"});
}

And in your client side you can check the result and show appropriate information to user.

$.post("someValidUrl",$("#form1").serialize(),function(response){
  if(response.Status=="Error")
  {
     alert(response.Message);
  }
});

You can send the Markup of your partial view in the JSON result (in the case of success) and use that to replace the html of your div which you want to update the content with. Check this answer for an extension method which does so.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • what about the validation then? It wont appear – AAlferez Jun 12 '13 at 14:45
  • You can send the validation messages also in the JSON data. – Shyju Jun 12 '13 at 14:46
  • you can get the validation error like this http://stackoverflow.com/questions/15296069/how-to-figure-out-which-key-of-modelstate-has-error/15296109#15296109 – Shyju Jun 12 '13 at 14:48
  • in this example you are sending the result as an `ActionResult` and you are talking about `Json` – AAlferez Jun 12 '13 at 14:53
  • You can send JSON from an action method which has return type `ActionResult'. You can return JSon/Image/PDF/String etc... – Shyju Jun 12 '13 at 14:59