0

I am currently building a ASP.NET MVC Project, and came accross some problem. I have a form that consist of a simple input and a grid input that looks like this

Invoice Code: XXX 
Customer: XXX 
Email: XXX

Item Code | Quantity | Price | 
XXX       | XXX      | XXX   |

The List's item line is dynamically appended using jquery and partial view.

Now that i want to give server side validation to the form, i read a guide that i have to add modelstate error in the [HttpPost] Action, and then return the submitted model along with the error back to the view, like this:

[HttpPost]
    public ActionResult New(Invoice InvoiceVM)
    {
        if (!ModelState.IsValid)
        {
            ModelState.AddModelError("INV_QUAN", "QUANTITY INVALID!");
            return View(InvoiceVM);
        }
        var INV_ID = SaveInvoice.NewInvoice(InvoiceVM);
        return RedirectToAction("Index");
    }

But when the validation triggered by an invalid input and it tried to return to the view along with the error, the view is obviously refreshed to the form that have no list's line, because the list's line item is appended dynamically.

Can anyone help me with this problem, how do i return to the view where the form already have the inserted line item in it. Or is there any workaround regarding my problem? thanks.

Ps: Sorry for the bad english

dimas bex
  • 11
  • 1

2 Answers2

0

You can send your form with ajax, then return redirect url or errors and append it to form dynamically like this:

Returning Partialview & JSON from MVC 5 Controller

MVC Return Partial View as JSON

Evgeny Zagorulko
  • 127
  • 4
  • 11
0

You have to change your model and store all needed data in it.

 public class SomeModel {
public Invoice InvoiceVM {get; set;}
public IList<SomeType> SomeData {get; set;}
}

Fill in model before send it to view:

    public ActionResult New(Invoice InvoiceVM)
    {
if (!ModelState.IsValid)
        { var model = new SomeModel {InvoiceVM =InvoiceVM;
           SomeData = _someService.GetData()};
            ModelState.AddModelError("INV_QUAN", "QUANTITY INVALID!");
            return View(model);
        }
Lapenkov Vladimir
  • 3,066
  • 5
  • 26
  • 37