This question already has answers here:
how to create a view with multiple models mvc 4?
(2 answers)
Closed 7 years ago.
I've been trying to dissect an automated MVC view & controller, and modify it so that i can insert information from a form in the view, on to two separate database tables (Entity framework database first).
here's what i have so far. it works if i reference either of the namespaces at the top on their own, but not together?
#model manage.mysite.DataModels.Property_Type
#model manage.mysite.DataModels.Room_Type
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Property_Type</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.PropertyType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PropertyType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PropertyType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RoomType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RoomType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RoomType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
It is not possible to reference several models in a View.
However, you can create composite model, which has the two other models as properties.
As such:
using manage.mysite.DataModels;
namespace manage.mysite.ViewModels
{
public class FooViewModel
{
public Property_Type PropertyType { get; set; }
public Room_Type RoomType { get; set; }
}
}
And then serve this model instead.
#model manage.mysite.ViewModels.FooViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Property_Type</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.PropertyType.PropertyType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PropertyType.PropertyType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PropertyType.PropertyType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RoomType.RoomType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RoomType.RoomType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RoomType.RoomType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
See also:
MVC Multiple Models in One View
how to create a view with multiple models mvc 4?
Which is the best way to use multiple models with sames properties and using a unique view?
Related
i am bit new in asp.net mvc. i am facing problem for very basic things that my Partial view not rendering. here is the details
i have a main page and one partial view
main page action look like
public ActionResult Index()
{
return View();
}
main index view look like
#model Testing.Models.Employee
#{
ViewBag.Title = "Home Page";
}
<div class="row">
</div>
<div class="row">
<div id="formsIndex">
#{
Html.Partial("_TestForm");
}
</div>
</div>
#section scripts {
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
}
here i am showing a partial view like this way Html.Partial("_TestForm"); but no UI comes for partial view.
partial view code look like
#model Testing.Models.Employee
#using (Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "formsIndex" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
</div>
}
when i pass model to partial view this way Html.Partial("_TestForm", Model); then also no UI comes.
please tell me where i made the mistake ?
use in method return PartialView() and try this
#Html.Partial("_TestForm");
Using Html.Partial inside a #{ ... } block will just call the method and throw the result away.
You should call it outside of a #{ ... } block, prefixed with #, and remember to pass in the model:
<div id="formsIndex">
#Html.Partial("_TestForm", Model);
</div>
Render like this
#Html.Action("_Partialview", "controllerName")
also create action methode of partial view
public ActionResult _Partialview
{
Employee _objModel= new Employee ()
return PartialView(_objModel);
}
This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 6 years ago.
i would like to get the list of checkboxes to the controller.
foreach (var item in Model.Billeder)
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(ModelItem => item.Overskrift, htmlAttributes: new { #class = "control-label col-md-2" }) #Html.DisplayFor(model => item.Overskrift)
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(ModelItem => item.Emailbool)
#Html.ValidationMessageFor(ModelItem => item.Emailbool, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Send" class="btn btn-default" />
</div>
</div>
in tilbud i have a
public virtual ICollection<Billed> Billeder { get; set; }
i would like for it to come into the controller so i can sort them
public ActionResult MailTilbud(Tilbud tb)
The for-each loop wouldn't work because the checkbox element name wouldn't be properly created with index which would cause it to be not posted back in controller, so change it to use for loop :
for (int i=0 i <Model.Billeder.Count; i++)
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(ModelItem => Model.Billeder[i].Overskrift, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DisplayFor(model => Model.Billeder[i].Overskrift)
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(ModelItem => Model.Billeder[i].Emailbool)
#Html.ValidationMessageFor(ModelItem => Model.Billeder[i].Emailbool, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
and you would need to modify your model to have IList<T>, as ICollection<T> does not have indexing support.
public virtual IList<Billed> Billeder { get; set; }
and if the above property is in your model which is mapped to a table using Entity Framework, then you would need to create ViewModel class specific to view instead of modifying the DTO model.
I have a view that contains 2 partial views.
#model ListViewModel
....
#{
Html.RenderPartial("EditCartItemsPartical");
Html.RenderPartial("ShowProductINFO", Model.Products);
}
and I just want to create a from with the first partial, and a list with the second.
The partial views
EditCartItemsPartical.cshtml
#model TestNewATM3._0.Models.CartItem
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.CartId, "CartId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CartId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CartId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductId, "ProductId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductId, "", new { #class = "text-danger" })
</div>
</div>
.... // more control for CartItem
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
ShowProductINFO.cshtml
#model IEnumerable<TestNewATM3._0.Models.AllProduct2>
<p>#Html.ActionLink("Create New", "Create")</p>
<table class="table">
<tr>
<th>ID</th>
<th>#Html.DisplayNameFor(model => model.Title)</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(model => item.Id)</td>
<td>#Html.DisplayFor(modelItem => item.Title)</td>
</tr>
}
</table>
And in my controller I got this.
public ActionResult Edit()
{
var db = ApplicationDbContext.Create();
var list = new ListViewModel
{
Products = db.AllProduct2s.ToList(),
Users = db.Users.ToList(),
Cart = db.Carts.ToList(),
CartItem = db.CartItems.ToList()
};
return View(list);
}
But the problem is that I cant show both partial at the same time because if I send the list in my view, then my first partial gets a problem cause it want a #model TestNewATM3.0.Models.CartItem. but if I don't sent the list My list wont show because I don't send it.
So how do i show a normal partial form view and a List partial view at the same time?
I'm having a little difficulty understanding your examples (i.e you have an edit view with create buttons), it looks like your trying to create a view to edit the cart.
Note: I would suggest renaming the CartItem property of your model to CartItems for clarity, but I'll use the current property names for the examples below.
You could render the partial view for each of the items in the list like so,
but this approach more is more than a little messy:
foreach(var cartItem in Models.CartItem){
Html.RenderPartial("EditCartItemsPartical", cartItem);
}
A simpler and more performant approach would be to edit the first view so it takes a collection of cart items
Like so
#model IEnumerable<TestNewATM3._0.Models.CartItem>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#foreach(var modelItem in Model.CartItem){
<h4>CartItem</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => modelItem.CartId, "CartId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => modelItem.CartId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => modelItem.CartId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductId, "ProductId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => modelItem.ProductId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => modelItem.ProductId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Aantal, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => modelItem.Aantal, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => modelItem.Aantal, "", new { #class = "text-danger" })
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
Of course this will require you to change the server side code to receive a collection of cart items, but from the user's perspective not having to post a form back multiple times, to complete your changes is going to result in a better experience.
disclaimer: I changed the above view in notepad, might need to adjust a bit before it works perfectly
I hope this helps.
Hi I am trying to default a date with 'DateTime.Now' in a create view. And setting an 'Active' field to 'true'
The following code does that in the the following action in the controller:
// POST: RequestTypes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,RequestTypeDescription,LastUpdated,Active,Team")] RequestType requestType)
{
if (ModelState.IsValid)
{
db.RequestTypes.Add(requestType);
requestType.LastUpdated = System.DateTime.Now;
requestType.Active = true;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.Team = new SelectList(db.Teams, "Id", "TeamDescription", requestType.Team);
return View(requestType);
}
That is the httppost code which defaults when the save is made.
What I want to do is to default those fields so that they show when the create view first gets launched - with the following code in the following action:
// GET: RequestTypes/Create
public ActionResult Create()
{
ViewBag.Team = new SelectList(db.Teams, "Id", "TeamDescription");
ViewBag.LastUpdated = System.DateTime.Now;
return View();
}
My Create View code is the standard created by MVC scaffolding:
#model ManageHR5.Models.RequestType
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>RequestType</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.RequestTypeDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RequestTypeDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RequestTypeDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastUpdated, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastUpdated, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastUpdated, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Active, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Team, "Team", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Team", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Team, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")}
When I run the app, and launch the create page, the defaults don't show up when the create page is launched.
What am I not understanding?
(A newbie to MVC :( )
You set them in the model on the Get for display purposes
// GET: RequestTypes/Create
public ActionResult Create() {
ViewBag.Team = new SelectList(db.Teams, "Id", "TeamDescription");
var model = new RequestType();
model.LastUpdated = System.DateTime.Now;
model.Active = true;
return View(model);
}
But like indicated in the provided comment
You set them immediately before you save the object in the POST method
I'm working with a standard razor view with form data. I want to pass the input form data to my controller after pressing the submit button. My view looks like this:
#model CareSource.ReleaseAssistant.Models.Prime.Team
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create New Team</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Team</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Abbreviation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Abbreviation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Abbreviation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedOn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedOn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedOn, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ModifiedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModifiedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModifiedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ModifiedOn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModifiedOn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModifiedOn, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
The problem is that the information in the form is not being passed back to my controller to be handled by my action method. I'm trying create a new entry in my database using web api. My action method looks like this:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
if (ModelState.IsValid)
{
HttpEndPointContext httpEndPoint = new HttpEndPointContext()
{
AuthenticationMethod = HttpAuthenticationMethods.None,
Ssl = false,
HttpMethod = HttpMethod.Post,
//Path = "localhost:32173/api/team/",
QueryStrings = null,
};
IProcessResult result = HttpConnectionManager.Current.SendMessage(httpEndPoint);
var response = result.ResponseData.ToString();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Most of the code in this project was generated using Codesmith Generator and uses the MicroORM called PetaPoco.
Since your form is strongly typed to an instance of Team and you are using that to generate the input form fields, you can use Team object as the parameter of your HttpPost method.
HttpPost]
public ActionResult Create(Team model)
{
if (ModelState.IsValid)
{
//access model.Properties
}
return View(model);
}
Do use Team model as parameter remove formCollection and try
Please update your View with the given code :
#using (Html.BeginForm("Create", "YourControllerName", FormMethod.Post, new { id = "form" }))
{
//Copy your current code as it is here.
}