How to add subitem with new item in asp.net MVC? - c#

I have simple code first model (image: https://ufile.io/7c52a)
I have a problem, when I want to add a new bill. When I add a new bill, I also want to add products on that bill (insert data into Pr_bi table).
My bill entity:
public class Bill : Entity
{
public string Number { get; set; }
public DateTime TimeStamp { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<Product_Bill> Product_Bill { get; set; }
}
My product entity:
public class Product : Entity
{
public string Name { get; set; }
public virtual ICollection<Product_Bill> Product_Bill { get; set; }
}
My pr_bi entity:
public class Product_Bill : Entity
{
public int Quantity { get; set; }
public virtual Bill Bill { get; set; }
public virtual Product Product { get; set; }
}
I create create view model like that:
#using (Html.BeginForm("Create", "Bill", FormMethod.Post, new { #class = "form-horizontal" })){
#Html.HiddenFor(m => m.ID)
<div class="form-group">
<label class="col-sm-2 control-label">Bill number:</label>
<div class="col-sm-6">
#Html.TextBoxFor(m => m.Number, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Payed:</label>
<div class="col-sm-6">
#Html.EditorFor(x => x.Payed)
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Customer:</label>
<div class="col-sm-6">
#Html.DropDownListFor(m => m.Customer.ID, ViewData["Customers"] as SelectList, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6"><input type="submit" value="Shrani" class="btn btn-default" /></div>
</div>}
How can I add product on that bill inside that create view for a bill?
What do I have and what I like:
Screen
Thank you and have a nice day!

Related

Why does this text-field send data properly but it is received as Null and Visual Studio raises exception?

I send data from view to action. Chrome browser shows that Genre_Id is sent properly as it you see the attached screenshot but when it is received by the action, Visual Studio raises exception and shows it as Null / 0 as you see the attached screenshot. So why does this happen?
this is Movie Model
public class Movie
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[Required]
[Display(Name="Created on")]
public DateTime DateAdded { get; set; }
[Required]
[Display(Name = "Release Date")]
public DateTime ReleaseDate { get; set; }
[Required]
[Display(Name = "Number in Stock")]
public int NumberInStock { get; set; }
public Genre Genre { get; set; }
[Display(Name="Genre")]
public int Genre_Id;
}
this is the Form
#using(Html.BeginForm("Save", "Movies"))
{
<div class="form-group">
#Html.LabelFor(m => m.Movie.Name)
#Html.TextBoxFor(m => m.Movie.Name, new { #class="form-control"})
</div>
<div class="form-group">
#Html.LabelFor(m => m.Movie.DateAdded)
#Html.TextBoxFor(m => m.Movie.DateAdded, new { #class="form-control"})
</div>
<div class="form-group">
#Html.LabelFor(m => m.Movie.ReleaseDate)
#Html.TextBoxFor(m => m.Movie.ReleaseDate, new { #class="form-control"})
</div>
<div class="form-group">
#Html.LabelFor(m => m.Movie.NumberInStock)
#Html.TextBoxFor(m => m.Movie.NumberInStock, new { #class="form-control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Movie.Genre_Id)
#Html.TextBoxFor(m => m.Movie.Genre_Id, new { #class="form-control"})
</div>
#Html.HiddenFor(m => m.Movie.Id)
<button type="submit" class="btn btn-primary">Save</button>
}
Look at the icons, the Genre_Id member looks different. That's because it's a field, not a property.
MVC requires model members to be properties. Add { get; set; } to its declaration.

TextboxFor element and CheckboxFor element are null and not sent to POST

I have a weird situation where we have this view model:
public class AddCommunicationViewModel
{
public Guid Id { get; set; }
public Guid ParentCommunicationGroupId { get; set; }
public Guid ParentCommunicationGroupCampaignId { get; set; }
public List<SelectListItem> CommunicationTypes { get; set; }
public CommunicationType SelectedCommunicationTypeId { get; set; }
[AllowHtml]
public string Subject { get; set; }
[AllowHtml]
public string Content { get; set; }
public string Reference { get; set; }
public bool AttachDemand { get; set; }
public int CommunicationSortingIndex { get; set; }
public string CommunicationGroupName { get; set; }
public AddCommunicationViewModel()
{
CommunicationTypes = new List<SelectListItem>();
}
}
Now, I have a very simple form (using Html.BeginForm) which posts to the controller:
#using (Html.BeginForm("UpdateSavedCommunication", "Communication", FormMethod.Post, new { id = "saveCommunication" }))
{
#Html.HiddenFor(c => c.ParentCommunicationGroupCampaignId)
#Html.HiddenFor(c => c.ParentCommunicationGroupId)
#Html.HiddenFor(c => c.Id)
<div class="form-group">
#Html.LabelFor(c => c.SelectedCommunicationTypeId)
#Html.DropDownListFor(c => c.SelectedCommunicationTypeId, Model.CommunicationTypes, new { #class = "form-control" })
</div>
<div class="div_subject form-group email">
#Html.LabelFor(c => c.Subject)
#Html.TextBoxFor(c => c.Subject, new { #class = "form-control" })
</div>
<div class="div_content form-group mb-3">
#Html.LabelFor(c => c.Content)
<div class="card-body">
<form class="form-horizontal form-bordered">
<div class="form-group row">
<div class="col-sm-12">
<textarea name="Content" id="summernote" class="summernote" data-plugin-summernote data-plugin-options='{ "height": 280, "codemirror": { "theme": "ambiance" } }'>
#Html.Raw(Model.Content)
</textarea>
</div>
</div>
</form>
</div>
</div>
<div class="div_reference form-group email">
#Html.LabelFor(c => c.Reference)
#Html.TextBoxFor(c => c.Reference, new { #class = "form-control" })
</div>
<div class="div_attachdemand form-group mb-3">
<div>
#Html.LabelFor(c => c.AttachDemand)
#Html.CheckBoxFor(c => c.AttachDemand)
</div>
</div>
<input type="submit" class="btn btn-success" value="Gem" onclick="document.getElementById('saveCommunication').submit();" />
}
The reason my "Content" variable is a bit weird, is because I user the Summernote editor. When I click the submit button all posts fine without any JavaScript errors.
However, now the weird stuff comes.
My variables: Reference and AttachDemand is NOT posted to server. Looking at Fiddler, I can see this is the post:
ParentCommunicationGroupCampaignId=00000000-0000-0000-0000-000000000000&ParentCommunicationGroupId=00000000-0000-0000-0000-000000000000&Id=2953bc1b-49e5-4f65-8159-1c53de5c82e8&SelectedCommunicationTypeId=2&Subject=&Content=++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++%3Cp%3E%3Cspan+style%3D%22color%3A+rgb%280%2C+0%2C+0%29%3B%22%3EHej%C2%A0*%7CNAME%7C*.%C2%A0%3C%2Fspan%3E%3C%2Fp%3E%3Cp%3E%3Cspan+style%3D%22color%3A+rgb%280%2C+0%2C+0%29%3B%22%3E*%7CCREDITORNAME%7C*+har+bedt+os+inddrive+din+g%C3%A6ld+hos+dem.+Der+er+tale+om+en+g%C3%A6ld+p%C3%A5%3C%2Fspan%3E%3Cspan+style%3D%22color%3A+rgb%280%2C+0%2C+0%29%3B%22%3E%C2%A0%3C%2Fspan%3E%3Cspan+style%3D%22color%3A+rgb%280%2C+0%2C+0%29%3B%22%3E*%7CDEMANDLINK%7C*+kr%2C+som+du+bedes+betale.%3Cbr%3EVi+har+vedh%C3%A6ftet+kravet+i+dette+brev+p%C3%A5+e-mail.%3C%2Fspan%3E%3C%2Fp%3E%3Cp%3E%3Cspan+style%3D%22color%3A+rgb%280%2C+0%2C+0%29%3B%22%3EDet+er+vigtigt+at+du+betales+denne+g%C3%A6ld+hurtigst+muligt%2C+for+at+undg%C3%A5+at+der+p%C3%A5l%C3%B8ber+ekstra+renter+samt+en+registrering+hos+RKI+og+som+videre+konsekvens+sendt+til+fogedretten.%3C%2Fspan%3E%3C%2Fp%3E%3Cp%3E%3Cspan+style%3D%22color%3A+rgb%280%2C+0%2C+0%29%3B%22%3ESE+DIN+SAG+OG+BETAL%3A+*%7CDEMANDLINK%7C*%C2%A0%3C%2Fspan%3E%3C%2Fp%3E%3Cp%3E%3Cspan+style%3D%22color%3A+rgb%280%2C+0%2C+0%29%3B%22%3E%3Cbr%3E%3C%2Fspan%3E%3C%2Fp%3E%3Cp%3E%3Cspan+style%3D%22color%3A+rgb%280%2C+0%2C+0%29%3B%22%3EVh%3Cbr%3E%3C%2Fspan%3E%3C%2Fp%3E%0D%0A++++++++++++++++++++++++%0D%0A++++++++++++++++++++++++%0D%0A++++++++++++++++++++++++%0D%0A++++++++++++++++++++++++%0D%0A++++++++++++++++++++++++&files=
Or in a view for humans:
So my challenge is: where is my Reference and AttachDemand ?
Now, if I move these two ABOVE the content editor, they work. So it seems that the Content is breaking because it sends some pretty cool HTML.
So any idea how to "make" this work? I guess I need to somehow escape the input in some smart way? I have added [AllowHtml] on the content attribute because it will contain HTML, but more than that?
Your view has nested forms which is invalid html and not supported (and depending on the browser and version, you may see different results).
Remove the inner <form class="form-horizontal form-bordered"> surrounding the textarea to ensure all from controls are serialized and sent in the request.

How to save data from Select box in Entity Framework Database relation Many to Many

How to save data from Select box in Entity Framework Database relation Many to Many
There are two classes one weapon and other User..
public class Weapon { } public class User { }
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
public class Wepon
{ public int ID { get; set; }
public string Wepon_Name { get; set; }
public int Power { get; set; }
}
Which should have relation Many to Many Using FormCollection and Model
User Class
And Weapon Class
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
**public List<Wepon> WeposInList { get; set; }**
}
public class Wepon
{
public int ID { get; set; }
public string Wepon_Name { get; set; }
public int Power { get; set; }
public List<User> UsersHaveWeponsList { get; set; }// User the List for M to M
}
DBContext
public class DbContexFor : DbContext
{
public DbContexFor()
: base("name=ConnectionStringName")
{
}
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Wepon> Wepons { get; set; }
}
}
**
The Controller Code
**
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name,Type")] User user, FormCollection formData)
{
if (ModelState.IsValid)
{
var ss = formData["ShipFromCountries"].ToString();
user.WeposInList = db.Wepons.Where(c => c.Wepon_Name == ss).ToList();
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
And the Html Code
#model enumVarAction.Models.User
#{
var list = ViewBag.MyList;
ViewBag.Title = "Create";
}
Create Html Page
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
#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.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WeposInList, htmlAttributes: new { #class = "control-label col-md-2" })
<select id="ShipFromCountries" multiple="multiple" name="ShipFromCountries">
<div class="col-md-10">
#foreach (var VARIABLE in list)
{
<option value="#VARIABLE.Wepon_Name">#VARIABLE.Wepon_Name</option>
}
</div>
</select>
</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")
}
**
Debug at Controller
**
**
Data is Database
**

EditorForTemplate inside a DisplayForTemplate MVC Razor

I was trying to use Html Display For Template for looping through a Model data. Inside my Display template, I wanted to use an EditorFor template that would display a different set of data, In doing so, I was running into issues where my child model was empty. Upon playing around and getting guidance from David, I was able to make this to work. Below, please find my updated working solution.
UPDATE (Correct solution)
public class TargetingAreaViewModel
{
public int DealerId { get; set; }
public int OrderId { get; set; }
public List<TargetingAreaOrderItemViewModel> TargetingAreaOrderItems { get; set; }
public TargetingAreaViewModel()
{
this.TargetingAreaOrderItems = new List<TargetingAreaOrderItemViewModel>();
}
}
public class TargetingAreaOrderItemViewModel
{
public int OrderItemId { get; set; }
public int PackageMediaTypeId { get; set; }
public string PackageMediaTypeHeader { get; set; }
public string MediaTypeDesc { get; set; }
public string TargetingAdditonalInfo { get; set; }
public List<TargetingAreaItemViewModel> TargetingAreaItems { get; set; }
public TargetingAreaOrderItemViewModel()
{
this.TargetingAreaItems = new List<TargetingAreaItemViewModel>();
}
}
public class TargetingAreaItemViewModel
{
public int OrderItemId { get; set; }
public int PackageMediaTargetingFieldId { get; set; }
public string TargetingAreaFieldTitle { get; set; }
public string TargetingValue { get; set; }
public bool IsEnabled { get; set; }
public bool IsRequired { get; set; }
public string Comment { get; set; }
}
Parent View
#model Models.TargetingAreaViewModel
#{
ApplicationContext.Current.PageTitle = "Targeting Info";
Layout = "~/Views/Shared/MainLayout.cshtml";
}
#using (Html.BeginForm("OrderItemTargetingInfo", "Home", FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.DisplayFor(m => m.TargetingAreaOrderItems)
<div class="col-sm-12">
<div class="pull-right">
<input id="Submit" type="submit" value="Submit" class="btn btn-primary" />
</div>
</div>
}
DisplayFor Template View
#model Models.TargetingAreaOrderItemViewModel
<div class="row">
<div class="col-sm-12">
<div class="col-sm-12 btn-primary" style="margin-bottom: 10px; margin-top: 10px;">
#Html.Label(Model.MediaTypeDesc, new { #style = "font-weight: bold; padding-top: 10px; font-size: 18px;" })
#Html.HiddenFor(m => m.OrderItemId)
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
#Html.Raw(Model.PackageMediaTypeHeader)
</div>
</div>
<br />
<div class="row">
<div class="col-sm-12">
#Html.EditorFor(m => m.TargetingAreaItems)
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<div class="form-group">
#Html.Label("Additional Info:", new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(m => m.TargetingAdditonalInfo, new { #class = "form-control" })
</div>
</div>
</div>
</div>
Now, I am able to display the data, get the data out of my model on Post. Works great!!
In your parent views you are only passing in the TargetingAreaOrderItems of the model but the child view is expecting a TargetingAreaViewModel. Instead you should pass in the entire model:
#Html.DisplayFor(m => m)

how to use multiple Checkbox in ASP.Net mvc3 Razor

In my ASP.Net MVC3 Razor project i have to implement a customer registration form(Screen Shot Attached).In that form , a single entity (say :purpose of doing DMIt) contains more than one answer.So i use checkbox to select the multiple or single answer.I have the view page and also a Model.How to code the View page to select multiple checkbox and also in Controller.
Controller Code
public ActionResult CustomerRegistration()
{
return View();
}
Model Code
namespace Elixir.Models
{
[Table("tbl_ElixirCustomer")]
public class Customer
{
[Key]
public int CusId { get; set; }
public string Name { get; set; }
public int age { get; set; }
public int Gender { get; set; }
public string FathName { get; set; }
public string MothName { get; set; }
public string OrgSchooName { get; set; }
public string Address { get; set; }
public string city { get; set; }
public string State { get; set; }
public string PIN { get; set; }
public string tele { get; set; }
public string Mob { get; set; }
public string Email { get; set; }
public string Web { get; set; }
public string Purpose { get; set; }
public string brief { get; set; }
}
public class CustomerViewModel
{
public string Purpose { get; set; }
public int Id { get; set; }
public bool IsChecked { get; set; }
}
}
View Code
<div class="col-lg-10">#Html.TextBoxFor(Model => Model.Mob, new { #class = "form-control" })</div>
<label class="col-lg-2 control-label">
Email</label>
<div class="col-lg-10">#Html.TextBoxFor(Model => Model.Email, new { #class = "form-control" })</div>
<label class="col-lg-2 control-label">
Web Site</label>
<div class="col-lg-10">#Html.TextBoxFor(Model => Model.Web, new { #class = "form-control" })</div>
<label class="col-lg-2 control-label">
Purpose of doing DMIT</label>
<div class="col-lg-10">
<div class="styled-chekbox">
<input type="checkbox" checked class="icheck-box-flat">
</div>
<span class="checkbox-label">Career Planning</span>
<div class="styled-chekbox">
<input type="checkbox" checked class="icheck-box-flat">
</div>
<span class="checkbox-label">Personel</span>
<div class="styled-chekbox">
<input type="checkbox" checked class="icheck-box-flat">
</div>
<span class="checkbox-label">Relationship</span>
<div class="styled-chekbox">
<input type="checkbox" checked class="icheck-box-flat">
</div>
<span class="checkbox-label">Parenting</span>
<div class="styled-chekbox">
<input type="checkbox" checked class="icheck-box-flat">
</div>
<span class="checkbox-label">Activity Plan for children</span>
<div class="styled-chekbox">
<input type="checkbox" checked class="icheck-box-flat">
</div>
<span class="checkbox-label">Stress Management</span>
</div>
<label class="col-lg-2 control-label">
Any Challenges</label>
<div class="col-lg-10">#Html.TextAreaFor(model => model.brief, new { #class = "tinymce-simple span12", #row = "170", #cols = "45", #width = "40%" })</div>
<div class="col-lg-2 control-label"></div>
<div class="col-lg-10">
#*<input type="button" class="" />*# #* <button type="submit" class = "btn btn-success">#Html.ActionLink("Save", "EmployeeRegistration", "Home")</button>*#
#* <button type="submit" >#Html.ActionLink("Save", "EmployeeRegistration", "Home", new { #class = "btn btn-success" })</button>*#
<input type="submit" class="btn btn-success" value="Save" />
<button class="btn btn-success">
Clear</button>
<button class="btn btn-success">
Cancel</button>
</div>
In CustomerViewModel you can have separate properties for every option
public bool CareerPlanning { get; set; }
public bool Personal{ get; set; }
public bool RelationShip{ get; set; }
and So on.....
Then in view you can have field for these properties
#Html.CheckBoxFor(Model => Model.CareerPlanning )<span> Career Planning </span>
#Html.CheckBoxFor(Model => Model.Personal)<span> Personal </span>
#Html.CheckBoxFor(Model => Model.RelationShip) <span> RelationShip</span>
and So on.....
Now in controller you need to modify Purpose depending on all checkbox value
StringBuilder sb=new StringBuilder();
if(model.CareerPlanning)
sb.Append("Carrer Planning");
if(model.Personal)
sb.Append("-Personal");
and so on....
and at the end
model.Purpose=sb.ToString();
Create a Boolean property in model
Model:
public String Question{ get; set; }
public Boolean Options{ get; set; }
public String OptionContent{ get; set; }
...so on
Pass this model into the view and then use EditorFor html helper.
#using (Html.BeginForm("actionname", "Home", FormMethod.Post, null)){
<div>
#Html.LabelFor(model => model.Question)
</div>
<div>
#Html.EditorFor(model => model.Option)
#Html.LabelFor(model => model.OptionContent)
</div>
}

Categories

Resources