0

Fresh ASP-MVC'er here.

My Model: Applications.cs, has a required string field: name.

MainView, showApps, shows all the apps in the DB in a table ... cleaned out code:

<tbody>
@foreach (var app in Model)
{
<tr>
<td>
// javascript code below that calls the Application/editApp action
<div id=@app.app_id.ToString() class="glyphicon glyphicon-pencil btn_edit_app" aria-hidden="true" style="color:blue; cursor:pointer"></div>
</td>
// other fields
<td><div id=@app.app_id.ToString() class="js_appname">@app.name</div></td>
// other app fields shown.
</tr>
}
</tbody>

Javascript code to call the Application/editApp:

 $('.btn_edit_app').click(function () {
        var app_to_edit = $(this).attr('id');

        $.ajax({
            url: '/Application/editApp',
            contentType: 'application/html; charset=utf-8',
            data: { app_id: app_to_edit },
            type: 'GET',
            dataType: 'html',
            success: function (result) {
                // dump the result in a dialog box with a tabbed div.
                $('#div_editapp_dialog').html(result);
                $('#edit_tabs').tabs({ active: 0 });
                $('#edit_dialog').dialog({ width: 700, height: 400 });
            }
        });        
    });

Application/editApp action:

[HttpGet]
public PartialViewResult editApp(int app_id)
{
    // get the app based on the app_id
    return PartialView("_EditApplication", app); 
}

I can view the tabbed form after executing the above code and it works good.

The problem I am having is with Model validation. When I go to save the form, I validate the model and in case it fails, I want it to go back to the same form with the fields. What would be the easiest/efficient way to go about it?

Application/saveApps

[HttpPost]
public ActionResult saveApps (Application app) 
{
  if (ModelState.IsValid) {
    db_context.applications.Add(app);
    db_context.SaveChanges();
    return RedirectToAction("showApps", "Application");
  }
// model validation failed, call the editApp action w/app_id             
  return RedirectToAction("editApp", "Application", new { app_id = app.app_id });
}

My last redirect doesn't seem to work. My guess is because JS calls to open the dialog in _EditApplication aren't there.

MAR
  • 95
  • 2
  • 7
  • you will want to do a partialViewResult method (retun partial view) For your validator method – DaniDev Nov 18 '17 at 00:56
  • You need to do an ajax form submit and when model validation fails, do `return View("_EditApplication",app);` assuming you have validation helpers in the partial view. – Shyju Nov 18 '17 at 01:00
  • thanks for the input .. had to do some more digging around re: Ajax forms ... I found this post, for those who land on this question, may find it helpful. I still have to try it out ... https://stackoverflow.com/questions/9577430/asp-net-mvc-form-validation-within-jquery-tab – MAR Nov 19 '17 at 06:44

0 Answers0