Why program shows empty result?

Asked by At

I create data field name "csPreRequest" and add to html form as model attribute like follow.

@GetMapping("/add")
public String addNewCourse(Model model) {

    String csPreRequest = "";
    model.addAttribute("csPreRequest",csPreRequest);

    return  "admin/add-course-module";
}

what i need to do is fill this field with my custom data and return back to controller class.I tried as follows:

@PostMapping("/save")
public String addNewCourse(@ModelAttribute("csPreRequest") String course) {

    System.out.println("\n Pre Reqest Courses : "+course+"\n\n");   

    return "redirect:/courses/add";
}

and my html code is like this:

      <input type="text" id="csPreRequest" th:field="${csPreRequest}">

my program work fines but nothing prints for result. what's went wrong here?

2 Answers

2
Ahmed Abdelhady On Best Solutions

In your GetMapping you're setting the model attribute with the variable csPreRequest which you initialized as an empty string, and an empty string is what gets rendered.

What you should be doing is: 1. When POST /save is called, then the value passed should be persisted. 2. When GET /add is called, it should retrieve the value persisted and set in the model.

0
AmirBll On

You should try @RequestParam when return back to controller:

@PostMapping("/save")
public String addNewCourse( @RequestParam("csPreRequest") String course ) {

    System.out.println("\n Pre Reqest Courses : "+course+"\n\n");   

    return "redirect:/courses/add";

}