MVC 4 model values not passed to controller action - asp.net-mvc-4

I have view and want to display content from the object stored in session one by one when user clicks on NEXT button. View uses WorldModel object to display the data. Id is hidden field and Content should be displayed on page.
View:
#model MvcApplication4.Models.WorldModel
#{
ViewBag.Title = "View1";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>View1</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<fieldset>
#Html.HiddenFor(model => model.Id)
#Html.DisplayFor(model => model.Content)
<input type="submit" value="Next" />
</fieldset>
}
Model: This class contains two properties id and content. Basically id is mapped to candidate id and Content is mapped to candidate name.
namespace MvcApplication4.Models
{
public class WorldModel
{
public int Id { get; set; }
public string Content { get; set; }
}
}
Controller: Class has two action methods one doesn’t take any parameter and other takes WorldModel as parameter.
namespace MvcApplication4.Controllers
{
public class WorldController : Controller
{
//
// GET: /World/
public ActionResult View1()
{
List<Candidate> obj = new List<Candidate>();
obj.Add(new Candidate() { Id = 1, Name = "ABCD", IsNameDispalyed = false});
obj.Add(new Candidate() { Id = 2, Name = "PQR", IsNameDispalyed = false });
obj.Add(new Candidate() { Id = 3, Name = "XYZ", IsNameDispalyed = false });
CandidateSession cs = new CandidateSession(){Candidates=obj};
Session["Can"] = cs;
return View();
}
[HttpPost]
public ActionResult View1(WorldModel worldModel)
{
CandidateSession cs = (CandidateSession)Session["Can"];
var can1 = cs.Candidates.Where(x => x.IsNameDispalyed == false).First();
can1.IsNameDispalyed = true;
return View(new WorldModel() {Id=can1.Id, Content=can1.Name });
}
}
public class Candidate
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsNameDispalyed { get; set; }
}
public class CandidateSession
{
public List<Candidate> Candidates { get; set; }
}
}
When I access URL as “../World/View1” it fills data to session object and click on NEXT button calls the action public ActionResult View1(WorldModel worldModel). In the method I get the object whose info is not displayed return the view with WorldModel object with id and Content. Now first time the Content is displayed but when the I click on NEXT button it call action public ActionResult View1(WorldModel worldModel). But the id and Content values of worldModel object are null. Why data is null, I set the values in the previous call?

Related

Passing Model via dropDownListFor() from view to controller

I am trying to pass a Model from my view to my controller using dropDownListFor.
After choosing something from the list it sends the model to my controller but it's content NULL.
This is what i have for the Model
public class Model
{
public int ModelId { get; set; }
[Required]
public string Name { get; set; }
}
This is what my ViewModel looks like
public class ModelVM
{
public List<Model> Models;
public Model SelectModel { get; set; }
public IEnumerable<SelectListItem> ModelItems
{
get { return new SelectList(Models, "ModelId", "Name"); }
}
}
The controller when i put data in the ViewModel looks like this
public ActionResult Index()
{
ModelVM modelVM= new ModelVM()
{
Models = manager.GetAllModels().ToList()
};
return View(modelVM);
}
Finally this is what i have in the View for the dropDownList
#using (Html.BeginForm("Home", "Home", FormMethod.Post))
{
#Html.DropDownListFor(model => model.SelectModel, Model.ModelItems)
<input type="submit" value="Go" />
}
So this is supposed to send Model to my controller.
But when i check the content of the passed Model in the controller, everything is NULL which isn't supposed to be because when i debug the view and check for the content of ModelItems, everything in the ModelItems is there.
Here is when i check the content of the passed Model
public ActionResult Home(Model model) <<<<<<<<<< Content == NULL
{
return View();
}
A <select> element on posts back a single value. Html has no concept of what your c# Model class is so you cannot bind to a complex object. You need to bind to the ModelId property of Model. Your view model should be
public class ModelVM
{
[Display(Name = "Model")]
public int SelectedModel { get; set; }
public SelectList ModelItems { get; set ;}
}
and in the controller
public ActionResult Index()
{
ModelVM modelVM = new ModelVM()
{
ModelItems = new SelectList(manager.GetAllModels(), "ModelId", "Name")
// SelectedModel = ? if you want to preselect an item
};
return View(modelVM);
}
and in the view
#Html.LabelFor(m => m.SelectedModel)
#Html.DropDownListFor(m => m.SelectedModel, Model.ModelItems)
and in the post method your model will be correctly bound with the ID of the selected model
Trying passing in type ModelVM to the Home action as that is the type being passed to Index view.
Instead of model.SelectModel in the drop-down declaration, you only need an int ID to capture which ID is selected.

Asp.net MVC , CheckBoxs not binding in case of list

Though it seems like it has been discussed earlier also , but I could not find the solution -:
I have a VM like this-:
public class RoomsVm
{
public RoomsVm()
{
Rooms.Add(new Room()
{
IsVip = true,Id = "1"
}
);
Rooms.Add(new Room()
{
IsVip = false,
Id = "2"
}
);
}
public List<Room> Rooms=new List<Room>();
}
public class Room
{
public bool IsVip { get; set; }
public string Id { get; set; }
}
My controller has 2 simple actions- 1- for get and 2 for post-:
public ActionResult IndexView2()
{
var roomVM = new RoomsVm();
return View(roomVM);
}
[HttpPost]
public ActionResult IndexView2(RoomsVm roomsVm)
{
return View(roomsVm);
}
In my view - I simply display my rooms with check boxes like this-:
#model MVCApplication.Models.RoomsVm
<h2>IndexView2</h2>
#using (Html.BeginForm())
{
for (int i = 0; i < Model.Rooms.Count(); i++)
{
#Html.CheckBoxFor(modelItem=>modelItem.Rooms[i].IsVip,new{value=Model.Rooms[i].Id})
}
<input type="submit" value="Submit"/>
}
Problem- When I click Submit button, I don't get updated values of rooms checkboxes in input value of Post action ..
What wrong am I doing ?
You don't have accessors on your Rooms property
public class RoomsVm
{
public RoomsVm()
{
Rooms = new List<Room>(); // Initialize rooms
Rooms.Add(new Room() {.... //Add rooms
}
public List<Room> Rooms { get; set; } // Add get/set
}

Passing List from View to Controller - MVC4

I am now kind of stuck here.
I have my Models here
namespace DSS.Models
{
public class SupplierItems
{
public string GroupID { get; set; }
public string GroupName { get; set; }
public List<SupplierLineItems> LineItems { get; set; }
}
}
and have Properties of Supplier Items are defined in Model as
namespace DSS.Models
{
public class SupplierLineItems
{
public string Frequency { get; set; }
public string UnitPrice { get; set; }
public int Index { get; set; }
}
}
My Controller is just hardcoding the Supplier Items and line items
namespace DSS.Controllers
{
public class HomeController : Controller
{
[HttpPost]
public ActionResult GetLineItems(SupplierItems SupplierItems)
{
return View();
}
public ActionResult Index()
{
List<SupplierLineItems> ListOfLineItems = new List<SupplierLineItems>();
SupplierLineItems LineItems = new SupplierLineItems();
LineItems.Frequency = "Regulate";
LineItems.UnitPrice = "20";
LineItems.Index = 1;
ListOfLineItems.Add(LineItems);
SupplierLineItems LineItems1 = new SupplierLineItems();
LineItems1.Frequency = "Regulate";
LineItems1.UnitPrice = "20";
LineItems.Index = 2;
ListOfLineItems.Add(LineItems1);
SupplierItems Items = new SupplierItems();
Items.GroupID = "1";
Items.GroupName = "Core Group";
Items.LineItems = ListOfLineItems;
return View(Items);
}
}
}
Here is my View
#model DSS.Models.SupplierItems
#using DSS.Models
#{
ViewBag.Title = "Home Page";
{
<a type="submit" href="#Url.Action("GetLineItems", "Home", Model)">#Model.GroupName</a>
<br />
foreach (var item in Model.LineItems)
{
#item.Frequency<br />
#item.UnitPrice<br />
#item.Index<br />
}
}
}
When I click on Anchor tag of my view and pass the Model to "GetLineItems" of Home Controller, My Supplier items get passed successfully but List of Line items always comes as null. I am not sure what is going wrong . Anyone, please help
enter code here
You should use ajax post to the controller or simply use form submission to achieve this
instead of using url.action which is an url form of submission

Multiple forms on mvc4 page, submit one form

I'm facing an issue with listing multiple forms, incl submit buttons.
When clicking the first button it posts correctly, but when I click the second submit button it submits an empty collection...
Below is my code:
Index.cshtml
#model MVCFormsSubmitting.Models.FormsRepository
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#for (int i = 0; i < Model.UserInfo.Count; i++)
{
using (Html.BeginForm("Index", "Forms", FormMethod.Post, new {name = "Form" + #i}))
{
<b>#Html.EditorFor(m => m.UserInfo[i].Name)</b>
<input name="button #i" type="submit" class="left btn btn-primary" value="Ret navne">
<br/>
}
}
Formsrepository.cs
namespace MVCFormsSubmitting.Models
{
public class Info
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
public class FormsRepository
{
public FormsRepository ()
{
this.UserInfo = new List<Info>();
}
public List<Info> UserInfo { get; private set; }
public async Task Load()
{
this.UserInfo.Clear();
UserInfo = await LoadUsers();
}
public async static Task<List<Info>> LoadUsers()
{
List<Info> info = new List<Info>();
info.Add(new Info(){
Age = "32,",
Email = "mail#mail.com",
Name = "John Doe",
Phone = "123456749",
Id = 0
});
info.Add(new Info()
{
Age = "36",
Email = "exmaple#example.com",
Name = "Jane Doe",
Phone = "987654321",
Id = 1
});
return info;
}
}
}
FormsController.cs
public class FormsController : Controller
{
//
// GET: /Forms/
public ActionResult Index()
{
FormsRepository.Load();
return View(FormsRepository);
}
[HttpPost]
public ActionResult Index(FormsRepository text)
{
return RedirectToAction("Index");
}
private static FormsRepository _repository;
public static FormsRepository FormsRepository
{
get
{
if (_repository == null)
{
_repository = new FormsRepository();
}
return _repository;
}
}
}
When setting a breakpoint at the HttpPost action in the Formscontroller you will see when clicking the submit button on the first will send 1 item, but when clicking the second button the item is null ...
please help :)
I did some changes to make this code work!
1) Change the controller/view to Render each UserInfo as a strongly typed partial view:
// This method will receive an info to process, so the model binder will build the model back in the server correctly
[HttpPost]
public ActionResult Index(Info userInfo)
{
return RedirectToAction("Index");
}
// This method will render a partial view for a user info
[ChildActionOnly]
public ActionResult GetUserInfo(Info userInfo)
{
return PartialView("_UserInfo", userInfo);
}
2) Change the view to render a partial view for each user info in the repository:
#model MVCFormsSubmitting.Models.FormsRepository
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#for (int i = 0; i < Model.UserInfo.Count; i++)
{
{Html.RenderAction("GetUserInfo", Model.UserInfo[i]);}
}
3) Create a Partial view to render an user info "_UserInfo":
#model MVCFormsSubmitting.Models.Info
#using (Html.BeginForm("Index", "Forms", FormMethod.Post, new { id = "Form" + #Model.Id, name = "Form" + #Model.Id }))
{
<b>#Html.EditorFor(m => m.Name)</b>
<input id="button_#Model.Id" name="button_#Model.Id" type="submit" class="left btn btn- primary" value="Ret navne">
<br/>
}
Try this:
....
using (Html.BeginForm("Index", "Forms", FormMethod.Post, new {name = "Form" + i.ToString()}))
....

"inline" editing in a mvc 4 list of objects

I have a strange problem and I don't know if this is actually possible.
What I want is, to be able to list all the values from my model and and edit them directly in the list.
Here's what I have:
Model Linker:
public class StoreLinkerModel
{
//public Guid? id { get; set; }
public IEnumerable<Stores> StoresAndOpeninghours { get; set; }
}
public class Stores
{
public long ID { get; set; }
public string StoreName { get; set; }
public string Address { get; set; }
public string Zip { get; set; }
public string City { get; set; }
}
My Controller:
public ActionResult Overview()
{
var model = new StoreLinkerModel
{
StoresAndOpeninghours = new[]
{
new Stores()
{
ID = 0,
Address = "Enghavevej 70"
},
new Stores()
{
ID=1,
Address = "Løngangsgade 30"
},
}
};
return View(model);
}
[HttpPost]
public ActionResult Overview(StoreLinkerModel model)
{
if (ModelState.IsValid)
{
var x = "go go go";
}
return RedirectToAction("Overview");
}
My overview.aspx page:
#model streetoffrs.web.Models.StoreLinkerModel
#{
ViewBag.Title = "Overview";
Layout = "~/Views/Shared/_dashboard.cshtml";
}
#Html.EditorFor(x => x.StoresAndOpeninghours)
and my EditorTemplate stores.aspx
#model streetoffrs.web.Models.Stores
#using (Html.BeginForm("Overview", "Dashboard", FormMethod.Post, new { name = "id" + #Html.DisplayFor(m => m.ID) }))
{
#Html.EditorFor(x => x.Address)
<input type="submit" class="left btn btn-primary" value="Ret butiksdata">
}
<br />
The list is being generated as it should, and when I hit the first button at the first editorfor it will post the model to my controller, but when I push the 2nd button, the model is null, but the first button still works!
Is this possible at all, if yes what am I missing, if not, tell me how I can accomplish this.
thanks in advance!
you need edit post action like this:
[HttpPost]
public ActionResult Overview(StoreLinkerModel model)
{
if (ModelState.IsValid)
{
var x = "go go go";
}
return View(model);
}
the RedirectToAction will be go to the first Overview Action,so you will be lost the data.