开发者

MVC3 Dropdown repopulates fine even on error postback, but suggestion on how to make it efficient - without introducing error

开发者 https://www.devze.com 2023-02-12 16:22 出处:网络
I can\'t post my code at the moment as I am on the road and out of office. Here is my code greatly simplified. I don\'t think I have a syntax issue as such - I think I need a clarification or, a point

I can't post my code at the moment as I am on the road and out of office. Here is my code greatly simplified. I don't think I have a syntax issue as such - I think I need a clarification or, a pointer.

Model:

[Validaton attribute]
class Data
{
   [Required]
   int xx
  ..
}

ViewModel:

class VM
{
  SelectItem Items;
  int ItemID;

  Data dt = new Data();
  public VM
  {
       Items =...  Load from db... 
  }

}
View

@Textbox xx (etc)
@DropDownFor(VM.ItemID, VM.Items

Controller

void Index
{
 VM vm = new VM();
//I also default some items here works well - I get a nice form all loaded.
  return View(vm);
}

[POST]
void Index(VM stuffPosted)
{

If ModelState.OK)(
{
     All good. We direct to another page with Redirect To Action
}

else
{
    return View(stuffPosted)
    //This is the problem case where I need an efficiency
}

PROBLEM

The form loads fine with the Index method. On postback submit, the ID comes back correctly in ItemID. If there is an error - the ModelState sends back the view...and all the selectio开发者_C百科n list(s) are in place, with selections. Oh joy! BUT, in the Postback method, the VM stuffposted instance class invokes the constructor and there is another (expensive) db call....to reload the collections..then the 'ViewState' seems to load the selected IDs over the top of it...

If I refactor the code so as there is no expensive reload of the collections...then I get the classic error along the lines of int32 but expecting IEnumerable and my original form does not show ...

I am missing something, clearly..how to reload the collection from 'ViewState' (page) for reuse in an error situation, and not need a db call.


You could use SessionState to avoid the database trip to repopulate the dropdown. Populate the SessionState on the first GET request, and then load from it when you need to repopulate the dropdown (on error) on POST. However be wary of the size of the collection you are storing in SessionState - you may be better going to the database after all to re-load the data.

0

精彩评论

暂无评论...
验证码 换一张
取 消