user1907849
user1907849

Reputation: 980

Form submission in partial views in MVC

I am developing a simple mvc application . The code is as follows:

Model .cs:

public class CustomModel
{ 
   public IEnumerable<lang> lstlang { get; set; }
   public IEnumerable<org> lstOrg { get; set; }
}

public class lang
{
   public int langid { get; set; }
   public string langName { get; set; }
}
public class org 
{
  public int orgId { get ;set;}
  public string orgName { get; set; }
}

Controller.cs

public Action Index()
{
   // Get data from database and fill the model
   var model = new CustomModel();
   return View(model);
}

public Action Partial()
{
   // Get data from database and fill the model
   var model = new CustomModel();
   return PartialView(model);
}

[HttpPost]
public Action Partial(FormCollection frm, CustomModel model)
{
   // Get data from database and fill the model
   var model = new CustomModel();
   return PartialView(model);
}

Index.cshtml

@model CustomModel
@Html.TextboxFor(x => x.lang.FirstOrDefault().id);
<input type="button" id="btn" />
@Html.RenderPartial("Partial", model)

Partial.cshtml

@model CustomModel
@Html.TextboxFor(x => x.lang.FirstOrDefault().id);
<input type="submit" id="submit" />

The thing is, when I click the submit button in the Partial.cshtml page, and examine the model in httppost method in public Action Partial(FormCollection frm, CustomModel model), the model contains null for both lists lstlang and lstOrg, but the formcollection[0] will give the selected textbox value.

What am I missing, or is this the right way of using partial views?

Upvotes: 1

Views: 1501

Answers (1)

Pharylon
Pharylon

Reputation: 9916

Don't use FirstOrDefault(). If you want to post something back to the front end with collections, you'll need to use indexing.

Public class CustomModel
{ 
   public ICollection<lang>  lstlang { get; set; }
   public ICollection<org> lstOrg { get; set; }
}


@HTML.textboxfor(x=>x.lang[0].id);

Upvotes: 3

Related Questions