jAdex
jAdex

Reputation: 584

Spring Boot - Return ResponseEntity with ModelAndView

I have a Thymeleaf form in a Bootstrap Modal, and I want to process it with jQuery - Ajax call. The form looks like this:

<form th:action="@{/model/new}" th:method="POST" th:object="${modelForm}" id="form-new-model">
    <div class="form-group">
        <label for="name"><strong>Model name</strong></label>
        <input type="text" class="form-control" th:classappend="${#fields.hasErrors('name')} ? is-invalid : '' " th:field="*{name}" aria-describedby="name" placeholder="My awesome model">
        <div class="invalid-feedback" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Error name</div>
    </div>
    <div class="form-group">
        <label for="description"><strong>Model description (optional)</strong></label>
        <textarea class="form-control" th:field="*{description}" rows="3" placeholder="Description"></textarea>
    </div>
    <div class="form-group row border-top align-items-center mb-0">
        <div class="col text-right mt-2">                              
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Add</button>
        </div>
    </div>
</form>

In the controller I have the following:

@PostMapping("/model/new")
public String newModel(@Valid modelForm modelForm, BindingResult bindingResult, RedirectAttributes attributes) {

    if(bindingResult.hasErrors()){
        attributes.addFlashAttribute("org.springframework.validation.BindingResult.dexModelForm", bindingResult);
        attributes.addFlashAttribute("modelForm", modelForm);
        return "project/modal-new-model";
    }

    // creating the object since it is valid
    // and returning success response with the new updated view

    return "";
}

So since I am processing the form with jQuery I have:

$(document).on('submit', '#form-new-model', function(e){
    e.preventDefault();
    const csrf = $(this).find('input[name="_csrf"]').val();
    $.ajax({
        type: 'POST',
        url: '/model/new',
        headers: {'csrf-token':csrf},
        data: $(this).serializeArray(),
        cache: false,
        success: function(data){
            // Here the controller needs to bring me a Success Response (No error).
            // And then I refresh specific parts of the whole view.   
        },
        error: function(data){
            // I need first to bring 'SOMETHING' from the controller that says is an error.
            // Here I have to update the form since I will return a view from the controller. 
        }
    });
});

So now the question is how can I control from the controller what response it is and to send with the response the specific HTML/Thymeleaf view?

Upvotes: 1

Views: 2812

Answers (1)

jAdex
jAdex

Reputation: 584

So I did a solution with ModelAndView.

ModelAndView mv = new ModelAndView();
mv.setViewName("project/form-new-model");
mv.setStatus(HttpStatus.BAD_GATEWAY);
return mv;

With status HttpStatus.BAD_GATEWAY is possible to catch in jQuery in error response and with HttpStatus.OK goes to jQuery success.

Upvotes: 1

Related Questions