MVC :: How To Post A List Model
Jan 18, 2011
Customer(Id,Name),
Phone(Id,CustomerId,Number)
Contact(Id,CustomerId,Name,Address)
In My Form
Customer Name : <Textbox>
Phone : <TextBox> <button> : button to Add More <Textbox> Phone to add multiple Phone
Contact Name : <TextBox>
Address : <TextBox> <button> : button to Add More Form Contact add multiple Contact
View 6 Replies
Similar Messages:
Dec 29, 2010
I have two model classes:
public class UserModel
{
public Guid Id { get; set; }
public string EmailAddress { get; set; }
public string LoginName { get; set; }
public string Password { get; set; }
}
public class GroupModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<UserModel> Users { get; set; }
}
I created a View (Create.Aspx) by inheriting GroupModel class.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MyApp.Models.GroupModel>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Create</title>
</head>
<body>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Id) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Id) %>
<%: Html.ValidationMessageFor(model => model.Id) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Name) %>
<%: Html.ValidationMessageFor(model => model.Name) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</body>
</html>
It is generating only two fields (Id, Name) in my aspx view. Also I am able to get the form data in the Model class object in Ñ‘[HttpPost]Ñ‘ request which contains the data for ID and NAME field in controller.
[HttpPost]
public ActionResult Create(GroupModel groupModel)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
How can I get the data in List<UserModel> object? I am thinking to Put a List control with checkboxes containing Users. Then catch them using FormCollection object in controller.
View 1 Replies
Nov 10, 2010
I have a requirement in my application that, while saving the application, need to get all the value from drop down list and pass it to the view model. But application should not allow the user to select more than one item from drop down list manually, ie, only one value at a time. My view model is like ...
public class ListManagement
{
public IEnumerable<selectListItem> InactiveProduct { get; set; }
public string[] InactiveProductSelected { get; set; }
public IEnumerable<selectListItem> ActiveProduct { get; set; }
}
[code]...
View 3 Replies
Jan 26, 2011
i wonder something about mvc post method. for example I created a view "strongly typed" from a model (MyModel).
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Demo1.Models.MyModel>" %>
for Create actionsthere is two way.
first one takes MyModel as parameter
[HttpPost]
public ActionResult cart(MyModel md, int someID)
{
//some code
//.....
return View(MyModel);
}
second one does not take parameter as model.
[HttpPost]
public ActionResult cart(int someID)
{
//some code
//.....
return View(Mymodel);
}
for first one way, after form post the form values does not delete, I mean form does not cleared,after second one form is be cleared. why this diffirence?
View 5 Replies
Mar 1, 2010
I have a single model type to wrap up various models I want to use in my view:
public class QuestionViewData {
public Question Question { get; set; }
public IList<Answer> Answers { get; set; }
}
Now, in my question view I pull the data from the Question object - that's fine. Secondly I iterate through all Answer objects and pass them to a partial view:
<% foreach(Answer item in Model.Answers) { %>
<% Html.RenderPartial("ShowAnswer", item); %>
<% } %>
For each answer (in the partial view) I have some action buttons (like ratings). I'm using separate form POST's with hidden fields for every button. The problem is that I can't post the whole QuestionViewData model to my action method cause I only have the Answer object as model in the partial view. However, I need to return the complete question view from that action that takes QuestionViewData as model.
View 2 Replies
Nov 23, 2010
For now, I just want to use HTTP POST to send json to asp.net mvc2 controller.Since the JSON is actually a list of JSON objects, and each of them has different fields & length, so it hard for me to make up a input model.So I want to know is there a way for me to post JSON without model/ajax to a controller in ASP.NET MVC2?
View 2 Replies
Jan 12, 2011
public class BandProfileModel
{
public BandModel Band { get; set; }
public IEnumerable<Relationship> Requests { get; set; }
}
and the following form:
<% using (Html.BeginForm()) { %>
<%: Html.EditorFor(m => m.Band) %>
<input type="submit" value="Save Band" />
<% } %>
which posts to the following action:
public ActionResult EditPost(BandProfileModel m, string band)
{
// stuff is done here, but m is null?
return View(m);
}
Basically, I only have one property on my model that is used in the form. The other property in BandProfleModel is just used in the UI for other data. I'm trying to update just the Band property, but for each post, the argument "m" is always null (specifically, the .Band property is null). It's posting just fine to the action, so it isn't a problem with my route. Just the data is null.
The ID and name attributes of the fields are BAND_whatever and Band.whatever (whatever being a property of Band), so it seems like it would work. What am I doing wrong? How can I use just one property as part of a form, post back, and have values populated via the model binder for my BandProfileModel property in the action?
View 2 Replies
Jun 5, 2010
I have an user view model that has the following properties:
public User user;
public List<Language> Languages;
I send the above model to the view and use html helpers to build the form, so I end up with something like:
<form action="/Users/Edit/5" method="post"><input id="user_UserId" name="user.UserId" type="hidden" value="5" />
First Name
Last Name
Email
Language
Now, I try to read the POST in something that initially was something like :
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Edit( int UserId, FormCollection form ) {
and cannot get the user.UserId variable, user.FirstName variable etc.
what needs to be done to be able to read this kind of POST request. I'm kind of reluctant to modifying my ViewModel as it is very simple and easy to maintain as it is.
View 2 Replies
Nov 4, 2010
I have a parent View that uses a few partial views. Each partial view has its own custom model. The parent View is a model containing each of the partial view's model. In other words this parent View model is NOT flat.
How do i get POST data to bind with the parent's model object? Do i have to write a custom model binder?
Update I'm not binding to a collection of objects of the same type (ie: a collection of uploaded files). I'm binding to object that contains multiple of objects. For example:
[code]....
View 1 Replies
Oct 12, 2010
I have recently started learning ASP.NET with MVC 2 Framework, I am facing difficulties in the following scenarios.In my MVC application I want to retain partial information in Model over post backs.Following is my scenario,
1. I initiate "Edit" of main record by clicking date hyperlink from left navigation.
2. Amend some data.
3. Save the record.
4. "Edit" sub record of the saved record by clicking another hyperlink from bottom left navigation panel.
The page is divided in to 6 tabs, the first 5 tabs shows the data for the main record and the 6th tab shows data of sub record. Wehn we "Edit@ sub record the previous 5 tabs doesn't have any changes noted, that means there is no harm in keeping their details intact in the main model. So is there a way to access model in the controller on hyper link click action so that I can only load the data for the clicked sub record (I am asking this, because the hyperlink click uses HTTP GET method so no model parameter passed in action method). If no, then how do I retain partial values in the Model over post backs?
Note that each tab data have been kept in individual models, and a main model has a collection member to hold all these individual models together.I thought as the model is binded with the view, it is too binded with controller. But it is allowing easily to access model in variable "Model" for the view but not for the controller.
View 3 Replies
Feb 17, 2011
I have the following code and it`s pointing out errors as follows
Error 1 The name 'date' does not exist in the current context
Error 2 The name 'person' does not exist in the current context
What is wrong?
$("#test").Click(function () {
var date = $("#DateFrom").val();
var person = Model.SelectedPerson;
$.ajax({
url: '@Url.Action("testEmp","Employee",new {dateFrom = date, selectedPerson= person})',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (result) {
$('#text).html(result);
},
});
return false;
});
View 1 Replies
Jul 25, 2010
I have a /Register [GET] Action in the controller that pre-poluates a view-model with a string and an integer and returns: return View(myModel);I can see the string being populated in the textarea and the id being populated in a hidden input. Yet when the form gets POSTed, the string value is null and the int value is 0. I verified that both values are posted to the server but the model received in the POST action is missing those values.
View 1 Replies
Apr 15, 2010
[Code]....
What I want to achieve is the ID of the property: item.Item.ID to be bound to the ID from the (route)URL. However I can't get it to work. I tried using [Bind()] attribute.
I fixed it now using a hidden field in the form like so:
<%= Html.HiddenFor(model => model.Item.ID)%>
However this feels a bit icky. I'd like to know if there is a better cleaner way of doing this?
View 1 Replies
Jan 6, 2011
I am using ASP.Net MVC2 and LINQ to SQL. I am using DataAnnotations and model binding in conjunction with a Form/View and its working beautifully well. Loving that.. My view is an "Add new Employee" form that's adding a new "Employee" complex object. Every Employee also has a child complex object called an "Address".
I am using the bound Html helpers in the view, such as Html.TextBoxFor(model => model.NewEmployee.FirstName) for example. Working beautifully well, validating beautifully well both client and server and coming into the controller fully populated and ready to be saved! Exciting.. ModelState.IsValid returns true and I go to save the new Employee.
The Employee is created fine but the system also creates a blank/new Address record in my Addresses table even when the Address fields are blank! How can I prevent any Address from being created, in situations where I ONLY want to create a new Employee with no Address. An example is when the user supplies an existing Address, then I wish to simply set the new Employee's AddressID to that of an existing physical address (I hope that makes sense). But it could apply to any situation where you need to create a new complex object, but you don't wish for LINQ to create any of its child complex objects. I have tried setting NewEmployee.Address = null after it is received in the controller, but even after that, a blank/new Address is still created. Even if I try NewEmployee.Address = SomeExistingAddress, it does correctly link the Employee to the existing Address, but it STILL goes off and creates another redundant new/blank address record! Which is really weird..
View 10 Replies
Jan 5, 2011
I have a "Create New Employee" ASP.Net MVC form. My complex object is an Employee and an Employee has an Address, which is another Complex object. On my View/Form I collect all required values for both the Employee and the Address. I'm using the bound HTML helpers such as: Html.TextBoxFor(model => model.EmployeeAddress.StreetName)
AND
Html.TextBoxFor(model => model.NewEmployee.FirstName)
This is all working beautifully well. Model binding is working like a dream, both server side and client side validation using DataAnnotations is working beautifully well and I am nicely receiving my populated complex objects as expected in the Controller.. Now I'm trying to save.. The Employee should always be newly created, because its an "Add New Employee" form. But sometimes the Address is an existing Address and I don't want to insert another one. Rather, I just want to link the Employee to the existing AddressID of the one that already exists in the database.
So I wrote a nifty GetExistingOrCreateNewAddress(Address PostedAddress) method which works great so I end up with the correct Address to use and link to the about to be saved Employee object. This is all happening in the same DataContext, so no problems there..
BUT even when I link the about to be saved Employee object to an existing Address, on save a new/empty Address row is created in my Addresses table. Even though the newly created Employee does link correctly to the existing Address I told it to! Why is it so??? And how can I save the new Employee without LINQ automatically creating a blank Address for me. Because I'm explicitly specifying an existing Address it should be linked to instead!
[HttpPost]
public ActionResult CreateEmployee(EmployeeDetailsViewModel NewEmployeeDetails)
{
if (ModelState.IsValid)
{
EmployeeRepository ER = new EmployeeeRepository();
// Fetch or Create the appropriate Address object for what has been entered
Address ActualAddress = ER.GetExistingOrCreateNewAddress(NewEmployeeDetails.EnteredAddress);
// Link this Address to the "about to be saved" Employee
NewEmployeeDetails.Employee.Address = ActualAddress;
// Lock it in..
ER.SaveNewEmployee(NewEmployeeDetails.Employee);
View 2 Replies
Nov 12, 2010
I've got a view model that has some text properties. And I use Html.DisplayFor to display them on the screen. But those text data won't be post back, so in the case of failed validation, the returned view won't have those data. How do I handle this kind of situation?
View 2 Replies
Jan 19, 2011
in my model there is a List.
public class InvoiceModel{
public int InvoiceID { get; set; }
public int Date { get; set; }[code]...
for create view i can use Html.TextBoxFor(m => m.InvoiceID) and for Date.but how can i fill List?and how can i use global for this list as Shopping cart?
View 6 Replies
Dec 30, 2010
I've a product model that contains a list of description models. Every description model contains some string values because every product can have a description for every language. Here it is a semplified version of my models:
[Code]....
So my view to insert a new product is like this:
[Code]....
And my PartialProductDescription view is like this:
[Code]....
Now, the views are perfect. With some Jquery UI I have a form with all the product properties and a tab panel with the language descriptions.
Unfortunatelly my POST action with the firm public ActionResult ProductNew(ProductModel model) has all the model property InternationalDescriptions that contain 2 empty models. So if I write something in the form in the first description textarea, model.InternationalDescrtiptions[0].Description is always empty.
So, how I can tell to MVC to take description textarea values and put them in the model?
View 6 Replies
Apr 17, 2010
I have a control that's bound to a list property. If I remove elements from that list using javascript and post, then the model gets updated, and the elements get removed.
Unless I remove all the items from the list. Then no names for that property go into the form data, and so the default model binder leaves the model's list untouched. This code from DefaultModelBinder.cs line 572 in the RTM sources makes it clear:
[Code]....
So how do I indicate to the model binder that I do want it to update the list and Ido want the list to be emptied?
View 3 Replies
Apr 29, 2010
I am trying set up a simple dropdown list but I dont seem to be able to get it to bind to the Model. I am using Asp.Net MVC and nhibernate.
My dropdown list is declared like so:
<%= Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewData["Projects"], " -- Select -- ", new { name = "Project" })%>
I set up the select list like so:
ViewData["Projects"] = new SelectList(projectRepository.GetAll(), "EntityGUID", "Name", editEntity.Project);
This seems to bind the select list to the Dropdown fine, but the SelectedValue is not set.
it shows up as the default --- Select ---
Also when I save this data, the dropdown does not bind to the model, I have to manually set the object like so to save it:
entity.Project = projectRepository.GetById(new Guid(Request["Project"].ToString()));
I believe I have take the correct messures to have this item bind directly to my model. Is there something I am missing here?
View 2 Replies
Feb 3, 2011
I am trying here to find a simple solution to bind an array of elements to a model using the MVC model binder. If I use the @Html.Checkbox helper now, it will generate me something like this :
[Code]....
I should be ok as it manage the checked in state and not checked in. The problem here is when I try to bind it back to the model (something really simple)
[Code]....
In the controller I try to bind it with the UpdateModel()
[Code]....
When I debug, the chk variable in the model is still null. I tried with IList<string>, bool[], IList<bool> nothing seems to make it. Is there any other way to deal with this else than form.GetValues("chk")[0].Contains("true") ?
View 3 Replies
Sep 25, 2010
Classic scenario - Categories, Subcategories and Products tables.
Subcategories belong to a corresponding main category
Products belong to a corresponding subcategory
The problem is that not all products do that. Some of them belong directly to a main category because that category has no subcategories. So if I wish to query those products I have to use a main category field in the products table.
And of course I need a subcategory field in the products table also for those products that do belong to a subcategory.
All that does not seem like a good normalized schema.
Now if I use the Adjacency list model the categories and subcategories tables become one (parentID column) and I only have to use a single CatId in my queries.
View 5 Replies
Mar 5, 2010
For a large fillin form I use the asp.net FormView for the magic databinding to my model. In this model I've a property called Rides (shown below), which exposes a list, which I obviously not want to be replaced entirely. So I made it readonly.
However, this way I can't use the databinding features anymore. Is there a common solution for this problem?
[code]....
View 3 Replies
Feb 18, 2011
i have a list of complex object let´s say: List<House>, inside of a model that i pass to the view.
To render that list i use the Html.EditorFor(x => x.list[i], "PartialView") inside of a div (<div id="editor"></div>). To "add" an item i use an ajax method that return a new partial view of the same type, an append it to the the div.
This way, the new partial it's appended but when i do the post, only the first item (list[0], the one that i pass in the controller to start) it´s bounded, but, the items added via ajax aren´t.
What could i do in this case? i wan't mi list to grow every time i hit the link that calls the ajax method and then take every item and add them to my database. i've followed this tutorials:
[URL]
[URL]
View 6 Replies
Mar 1, 2011
My problem here is how to send the list values to the controller upon an ajax post. With my actual code, the list is null on post.
My view:
[code]....
My controller:
[code]....
View 1 Replies