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.
Related
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
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?
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()}))
....
I am facing a problem that when I have a complex Model, if I submit the form it will not give me all the values of all the model properties, in the below example, I am not getting back the gridModel properties:
Model
public class InventoryModel {
public GridModel GridModel { get; set; }
public Int32 UserKey { get; set; }
}
public class GridModel {
public String GridId { get; set; }
public String GridName { get; set; }
public List<String> columns { get; set; }
}
Controller
public ActionResult Index(){
InventoryModel model = new InventoryModel();
model.UserKey= 20014;
model.GridModel = new GridModel();
model.GridModel.GridId = "jqgInventory";
model.GridModel.GridName = "Inventory Grid";
return View(model);
}
[HttpPost]
public ActionResult Index(InventoryModel model){
Int32 userId = model.UserKey; // This has a value
String gridId = model.GridModel.GridId; // This doesn't have a value
String gridName= model.GridModel.GridName; // This doesn't have a value
}
View
#model InventoryModel
#using (Html.BeginForm()) {
#Html.TextBoxFor(m => m.UserKey, new { #class = "w200" })
#Html.TextBoxFor(m => m.GridModel.GridId , new { #class = "w200" })
#Html.TextBoxFor(m => m.GridModel.GridName, new { #class = "w200" })
<input type="submit" value="Submit" />
}
Any suggestion please would be appreciated.
Thanks,
Alaa
You could instead use a ViewModel rather than the actual Model. This would be a flatter class that reflects the data specifically for the View.
public class InventoryViewModel{
Int32 UserKey {get; set; }
public String GridId { get; set; }
public String GridName { get; set; }
}
Your controller can map your model to your ViewModel if necessary
I'm trying to move over to MVC from webforms, and to be honest, it's not going very well.
I need a DropDownList populated with values from my database, and I'm having a hard time understanding how to do this.
I'm thinking, that I need to create a model,using entity framework, and refer my DropDownList to that? But how do I point it to that model?
Also, if I make a model, from a database table, how do I adjust the select command, so I only get certain values, and not the entire table?
I know this is kind of a broad question, and I have no examples listed, but I've had a really hard time, finding information I could understand, with regards to my issue.
I would start from this this should get you the project created if you have not done so so you can have the model ready
http://msdn.microsoft.com/en-us/data/gg685489
in order to create a dropdownlist here is an example
ViewBag.dropdownlist = new SelectList(db.tablename, "Valuefiled", "NameGField");
where Valuefiled=name of a column in your database that you want to use for values
"NameGField"=name of a column in your database that you want to use for names
getting drop down list to view
#Html.DropDownList("dropdownlist")
How About this
Your ViewModel
public class CategoryViewModel
{
public Category Category { get; set; }
public IEnumerable<SelectListItem> CategoryTitles { get; set; }
}
Your Controller
public ActionResult Create()
{
var categoryviewmodel = new CategoryViewModel();
categoryviewmodel.Category = new Category();
var list = categoryRepository.AllCategoryTitles().ToList().Select(t => new SelectListItem
{
Text = t.CategoryName,
Value = t.CategoryID.ToString()
})
.ToList();
list.Insert(0, new SelectListItem { Value = "0", Text = "Please Selext" });
categoryviewmodel.CategoryTitles = list;
return View(categoryviewmodel);
}
Your Repository
public IQueryable<Category> AllCategoryTitles()
{
var query = context.Categories.Where(m => m.ParentCategoryID == null && m.IsActive==true);
return query;
}
Your View
#Html.DropDownListFor(model => model.CategoryParentID, Model.CategoryTitles)
You can use a viewModel. Here is an example solution with some assumptions. Refer to the dropdownlist (here in the dropdown I am listing departments of type "InBound"
Employee Model
public class EmployeeModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int DeptId { get; set; }
}
Department Model
public class DepartmentModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
ViewModel (to be passed into the view)
public class EmployeeViewModel
{
public EmployeeModel Employee { get; set; }
public IEnumerable<DepartmentModel> Departments { get; set; }
}
Controller
public ActionResult Index()
{
EmployeeViewModel vm = new EmployeeViewModel();
//This is hardcoded. However you will write your own method to pull the department details with filtering
List<DepartmentModel> departments = new List<DepartmentModel>() { new DepartmentModel { Id = 1, Name = "Accounts", Type = "InBound" }, new DepartmentModel { Id = 2, Name = "Finance", Type = "OutBound" }, new DepartmentModel { Id = 3, Name = "HR", Type = "InBound" } };
vm.Departments = departments.Where(d => d.Type == "InBound");
return View(vm);
}
View
#model Test1.ViewModels.EmployeeViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.Employee.Id);
<table>
<tr>
<td>#Html.LabelFor(model => model.Employee.FirstName)</td>
<td>#Html.EditorFor(model => model.Employee.FirstName)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Employee.LastName)</td>
<td>#Html.EditorFor(model => model.Employee.LastName)</td>
</tr>
<tr>
<td>#Html.Label("Department")</td>
<td>#Html.DropDownListFor(model => model.Employee.DeptId, new SelectList(Model.Departments, "Id", "Name"))</td>
</tr>
</table>
}