As I am new to an ASP.NET Core 2.0 MVC I have a little demo app where I want to add a new entity of Type Lineup which has a ICollection of type Player in its model.
The involved classes are
public class Lineup
{
public int LineupID { get; set; }
public int PlayerID { get; set; }
public ICollection<Player> Attendants { get; set; }
}
and
public class Player
{
public int PlayerID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
My Create Lineup view looks like this
<form asp-action="Create">
<div class="form-horizontal">
<h4>Lineup</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Attendants" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Attendants" class="form-control"
asp-items="ViewBag.Players" multiple="multiple">
</select>
</div>
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
The ViewBag.Players is part of the LineupsController:
private void PopulatePlayersDropDownList(object selectedPlayer = null)
{
var playersQuery = from p in _context.Player
orderby p.Name
select p;
ViewBag.Players = new SelectList(playersQuery.AsNoTracking(), "PlayerID",
"Name", selectedPlayer);
}
That's how it looks so far:
but inside my Create method
public async Task<IActionResult> Create([Bind("Attendants")] Lineup lineup)
{
if (ModelState.IsValid)
{
_context.Add(lineup);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(lineup);
}
the Attendants count of the Lineup entity is 0 and not 2 as expected from the sample above. What is wrong here? Thanks for any help.
You need to instantiate your property when you create the object. Otherwise, the property is the default, which is null:
public class Lineup
{
public int LineupID { get; set; }
public int PlayerID { get; set; }
public ICollection<Player> Attendants { get; set; } = new List<Player>();
}
ok, these 2 steps solved my problem:
see answer of krillgar
changing the method signature of Create to
public async Task Create(int[] PlayerIDs)
{
...
}
Related
I'm somewhat new to MVC and have been following along with a tutorial but it has no answers regarding my question. For my Create page, the Foreign keys are not showing up. Basically, on the Projects page I created a project, on the People page I created a person. So when I try to create a ProjectRole on the ProjectRoles page, the ProjectId and PersonId are not showing up in the drop-down menu. Down below all of my code, I have provided a screenshot of what I have tried to put into words.
My models:
public class Project
{
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string Name { get; set; }
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime DueDate { get; set; }
public ICollection<ProjectRole> ProjectRoles { get; set; }
}
public class Person
{
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string FirstName { get; set; }
[Required]
[MaxLength(30)]
public string MiddleName { get; set; }
[Required]
[MaxLength(30)]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
public ICollection<ProjectRole> ProjectRoles { get; set; }
}
public class ProjectRole
{
public int Id { get; set; }
[Required]
public double HourlyRate { get; set; }
[ForeignKey("Person")]
public int PersonId { get; set; }
[ForeignKey("Project")]
public int ProjectId { get; set; }
[ForeignKey("AppRole")]
public int RoleId { get; set; }
}
My Controller code:
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,HourlyRate,PersonId,ProjectId,RoleId")] ProjectRole projectRole)
{
if (ModelState.IsValid)
{
_context.Add(projectRole);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(projectRole);
}
And my view code here:
#model Project2.Models.Entities.ProjectRole
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>ProjectRole</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="HourlyRate" class="control-label"></label>
<input asp-for="HourlyRate" class="form-control" />
<span asp-validation-for="HourlyRate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PersonId" class="control-label"></label>
<select asp-for="PersonId" class ="form-control" asp-items="ViewBag.PersonId"></select>
</div>
<div class="form-group">
<label asp-for="ProjectId" class="control-label"></label>
<select asp-for="ProjectId" class ="form-control" asp-items="ViewBag.ProjectId"></select>
</div>
<div class="form-group">
<label asp-for="RoleId" class="control-label"></label>
<input asp-for="RoleId" class="form-control" />
<span asp-validation-for="RoleId" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Screenshot of example of what I mean:
I suppose more personable to display the Person Name (and the Project Name) in the select controls, but to pass the PersonId (and ProjectId) to the Create method when click on the Create button.
Therefore, prepare the Person list (and the Project list) like below:
public IActionResult Create()
{
var persons = new List<SelectListItem>();
// Iterate through `Persons`
foreach(var p in _context.Persons)
{
persons.Add(new SelectListItem() { Value= p.Id, Text = p.FirstName+", "+p.LastName});
}
ViewBag.Persons = persons;
// Prepare the projects list (like `Persons` list above)
// ... your code here
ViewBag.Projects = persons;
return View(new ProjectRole(){ /* Add your code here to create the ProjectRole .../* });
}
And in the view:
<div class="form-group">
<label asp-for="PersonId" class="control-label"></label>
<select asp-for="PersonId" class="form-control" asp-items="ViewBag.Persons"></select>
</div>
<div class="form-group">
<label asp-for="ProjectId" class="control-label"></label>
<select asp-for="ProjectId" class="form-control" asp-items="ViewBag.Projects"></select>
</div>
For additional information see The Select Tag Helper
*NOTE: And I would recommend to create compound view model to include all required information. *
ViewModels or ViewBag?
Understanding Best Way to Use Multiple Models in ASP.NET MVC
I'm trying to render a List<PlayerCheckbox> as Checkboxes.
PlayerCheckbox looks like this:
(added empty constructor as per #jcwmoore 's answer, sadly nothing changed with this addition alone)
public class PlayerCheckbox
{
public PlayerCheckbox(string discordName, ulong discordId, bool selected = false)
{
DiscordName = discordName;
DiscordId = discordId;
Selected = selected;
}
public PlayerCheckbox()
{
}
public string DiscordName { get; set; }
public ulong DiscordId { get; set; }
public bool Selected { get; set; }
}
The CreateBingoTaskModel looks like this: (ViewModel I am working with on the Create page, added a default constructor here aswell per #jcwmoore 's input, just in case)
public class CreateBingoTaskModel
{
public CreateBingoTaskModel()
{
}
/// <summary>
/// Discord Id of the creator of this BingoTask
/// </summary>
public BingoPlayer Creator { get; set; }
[Range(0, 100)]
public int Difficulty { get; set; }
/// <summary>
/// List of IDs that are not allowed to receive this bingo task
/// </summary>
public List<BingoPlayer> BlackListIds { get; set; } = new List<BingoPlayer>();
/// <summary>
/// Title of this bingo task
/// </summary>
[Required]
public string BingoTitle { get; set; }
/// <summary>
/// Description of this bingo task
/// </summary>
[Required]
public string BingoDescription { get; set; }
public DateTime RaffledOn { get; set; }
public List<PlayerCheckbox> BlackList;
}
The setup GET-Create looks like this:
public async Task<IActionResult> Create()
{
CreateBingoTaskModel createBingoModel = new CreateBingoTaskModel();
createBingoModel.BlackList = new List<PlayerCheckbox>();
var user = await appDb.BingoPlayers.SingleOrDefaultAsync(player =>
player.LoginName == HttpContext.Session.GetString("user"));
foreach (BingoPlayer bp in appDb.BingoPlayers)
{
PlayerCheckbox playerCheckbox =
new PlayerCheckbox(bp.Name, bp.DiscordId);
if (playerCheckbox.DiscordId != user.DiscordId)
{
createBingoModel.BlackList.Add(playerCheckbox);
}
}
return View(createBingoModel);
}
The POST-Create looks like this:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateBingoTaskModel createBingoTaskModel)
{
if (ModelState.IsValid)
{
var user = await appDb.BingoPlayers.SingleOrDefaultAsync(player =>
player.LoginName == HttpContext.Session.GetString("user"));
foreach (PlayerCheckbox checkbox in createBingoTaskModel.BlackList)
{
if (checkbox.Selected)
{
var player = appDb.BingoPlayers.Single(bingoPlayer => bingoPlayer.DiscordId == checkbox.DiscordId);
createBingoTaskModel.BlackListIds.Add(player);
}
}
createBingoTaskModel.BlackListIds.Add(user);
BingoTask newBingoTask = new BingoTask
{
Difficulty = createBingoTaskModel.Difficulty,
BingoTitle = createBingoTaskModel.BingoTitle,
BingoDescription = createBingoTaskModel.BingoDescription,
BlackListIds = createBingoTaskModel.BlackListIds
};
appDb.Add(newBingoTask);
await appDb.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(createBingoTaskModel);
}
Looking at the Model in the POST-Create Header:
shows that the BlackList is now null.
I Do not understand why this is null, I was expecting all of the players except for the current logged in user, even if the logic was incorrect, .BlackList should at least be initialized.
The Checkbox List Code I am using looks like this:
#using App.API.Models
#model App.API.Models.CreateBingoTaskModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>BingoTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Difficulty" class="control-label"></label>
<input asp-for="Difficulty" class="form-control" />
<span asp-validation-for="Difficulty" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BingoTitle" class="control-label"></label>
<input asp-for="BingoTitle" class="form-control" />
<span asp-validation-for="BingoTitle" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BingoDescription" class="control-label"></label>
<input asp-for="BingoDescription" class="form-control" />
<span asp-validation-for="BingoDescription" class="text-danger"></span>
</div>
<div class="form-group">
<span>BlackList</span>
#for (int i = 0; i < Model.BlackList.Count; i++)
{
<input hidden asp-for="BlackList[i].DiscordId" />
<input hidden asp-for="BlackList[i].DiscordName" />
<input asp-for="BlackList[i].Selected" type="checkbox" />
#Model.BlackList[i].DiscordName
<br />
}
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
and is taken from this answer here:
https://forums.asp.net/t/2164304.aspx?Asp+net+MVC+Core+giving+null+checkbox+data+instead+of+all+selected+checkboxes+on+HTTPPost
Many implementations of CheckboxLists have extremely similar frontend code with the only major change being a replacement of for with foreach(playerCheckbox in BlackList) which I have tried too.
My FormData looks... fine? (Except the extra values at the bottom)
I do NOT understand at all why the binding doesn't work here. Am I so tired that I am overlooking somethingy extremely simple?
If more information / code is needed, I will gladly provide more context where needed.
To my knowledge, the model binder requires a default (parameterless) constructor in the model class. The model class is fine, but the PlayerCheckbox does not have a parameterless constructor. Try either removing your constructor, or adding a parameterless one, to the PlayerCheckbox class.
public class PlayerCheckbox
{
// default parameterless constructor to support deserialization
public PlayerCheckbox()
{
}
public PlayerCheckbox(string discordName, ulong discordId, bool selected = false)
{
DiscordName = discordName;
DiscordId = discordId;
Selected = selected;
}
public string DiscordName { get; set; }
public ulong DiscordId { get; set; }
public bool Selected { get; set; }
}
I´m having an issue where I have three models as show below: Person, Competence with PersonCompetence between them. My current controller method gets an Id from previous page and shows that person with a list of this person's Competence and Level. In this View however I want to have a POST for new Competence. So at the same time you are adding a new one and you can see which ones you already have.
With the controller method I have now I can access the PersonCompetence and Competence when showing the list.
I dont have access to the Competence properties for asp-for="Competence" marked ###### in the View for AddComp.
I need the ID of person for POST to right person
I need the CompetenceType for POST to that property
I need PersonCompetence to show the list of current PersonCompetence.
I get that with the current #model CompetenceRadar.Models.Person I only reach Person properties.
I have looked at having a ViewModel with access to all tables with an IEnumerable for each table, but this breaks my current Controller when I search for the Id of the person showing. I have switched the #model in the View, but then I can't access Person ID/name.
So how do I access the Competence properties , list one person and get a list of PersonCompetences for that Person.
Please tell me if you want me to clarify something.
I don't need working code, just something to point me in the right direction for a solution.
Is it a ViewModel?
Can I POST without the asp-forattribute?
Models
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public ICollection<PersonCompetences> PersonCompetences { get; set; }
}
public class PersonCompetence
{
public int ID { get; set; }
public int PersonID { get; set; } // FK
public int CompetenceID { get; set; } // FK
public int Level { get; set; }
public Competece Competence { get; set; }
public Person Person { get; set; }
}
public class Competence
{
public int ID { get; set; }
public string CompetenceType { get; set; }
public string CompetenceCategory { get; set; }
public ICollection<PersonCompetence> PersonCompetences { get; set; }
}
AddComp Kontroller function
public async Task<IActionResult> AddComp(int? id)
{
var person = await _context.Personer
.Include(pk => pk.PersonCompetences)
.ThenInclude(k => k.Competence)
.FirstOrDefaultAsync(m => m.ID == id);
return View(person);
}
View_AddComp View for AddComp
#model CompetenceRadar.Models.Person
<h1>AddComp</h1>
<div class="row">
<form asp-action="AddComp">
<input type="hidden" asp-for="ID" />
<div class="form-group col-sm-4">
<label asp-for="#############" class="control-label col-sm-4"></label>
<input asp-for="#############" class="form-control col-sm-4" />
<span class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-dark" />
</div>
</form>
</div>
#foreach (var item in Model.PersonCompetences)
{
<div class="row py-2 rounded" style="background-color:lightslategray">
<div class="col-sm-3 pt-2">#item.Competence.CompetenceType</div>
<div class="col-sm-1 pt-2">#item.Niva</div>
<div class="col-sm-3 pt-2">#item.Competence.CompetenceCategory</div>
<div class="col-sm-5 d-flex justify-content-end">
<a class="btn btn-dark mr-1" role="button" asp-area="" asp-controller="Competence" asp-action="UpdateLevel" asp-route-id="#item.ID">Update</a>
<a class="btn btn-dark mr-1" role="button" asp-area="" asp-controller="Competence" asp-action="DeleteComp" asp-route-id="#item.CompetenceID">Remove</a>
</div>
</div>
}
Simple anwser is that I needed a ViewModel with all three Models
public class ExampleViewModel {
public Person person { get; set; }
public PersonCompetence personCompetence { get; set; }
public Competence competence { get; set; }}
This alows me to access the different values for ID, CompetenceType and a List for of the current PersonCompetence.
What is ViewModel in MVC?
How do you properly bind a Dictionary and it's values per key to checkboxes?
I can display them in the HTTPGET but binding the selected values again to HTTPPOST doesn't seem to work.
viewmodel
public class EditViewModel
{
public Foo Foo { get; set; }
public Dictionary<Bar, List<BarVersionEditVM>> Matrix { get; set; }
}
public class BarVersionEditVM
{
public int ID { get; set; }
public string Name { get; set; }
public string Version { get; set; }
public bool IsSupported { get; set; }
}
view:
<form asp-action="Edit">
<div class="row">
#foreach (var kvp in Model.Matrix.OrderByDescending(x => x.Key.Name))
{
<div class="col-md-2 col-lg-2">
<fieldset>
<legend>#kvp.Key.Name</legend>
#foreach (var version in kvp.Value)
{
<div>
<input type="checkbox" id="#version.ID" value="#version.IsSupported" name="#version.Name" #(version.IsSupported ? "checked=\"checked\"" : "") />
<label>#version.Version:</label>
</div>
}
</fieldset>
</div>
}
</div>
<input type="hidden" asp-for="#Model.Foo.ID" />
<input type="submit" value="Save" class="btn btn-default" />
</form>
In the View I tried also to rewrite with foreach and using Html helpers, but without success:
#Html.CheckBoxFor(model => model.Matrix[kvpair.Key][i].IsSupported)
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EditViewModel vm) {
// vm is there but Matrix are null.
// and only the ID of Foo property is filled in.
}
any suggestions?
Unless your Dictionary has simple value types for both the Key and Value (e.g. public Dictionary<string, string>), the DefaultModelBinder requires that the form control name attributes be in the format
<input .... name="Matrix[0].Key" value="..." />
<input .... name="Matrix[0].Value[0].ID" value="..." />
<input .... name="Matrix[0].Value[0].Name" value="..." />
There are no HtmlHelper methods that will generate the correct html to allow binding to your Dictionary.
It is far simpler to create simple view model(s) to with IList<T> properties for the collections. Based on the view you have shown, those models would be
public class EditVM
{
public int FooID { get; set; }
public List<BarVM> Bars { get; set; }
}
public class BarVM
{
public string Name { get; set; }
public List<BarVersionVM> Versions { get; set; }
}
public class BarVersionVM
{
public int ID { get; set; }
public string Name { get; set; } // not clear where you use this property
public string Version { get; set; }
public bool IsSupported { get; set; }
}
and your view would then be
#model EditVM
....
#Html.HiddenFor(m => m.FooID)
#for(int i = 0; i < Model.Bars.Count; i++)
{
<fieldset>
<legend>#Model.Bars[i].Name</legend>
#Html.HiddenFor(m => m.Bars[i].Name) // in case you need to return the view in the POST method
#for(int j = 0; j < Model.Bars[i].Versions.Count; j++)
{
<div>
#Html.HiddenFor(m => m.Bars[i].Versions[j].ID)
#Html.CheckBoxFor(m => m.Bars[i].Versions[j].IsSupported)
#Html.LabelFor((m => m.Bars[i].Versions[j].IsSupported, Model.Bars[i].Versions[j].Version)
</div>
}
</fieldset>
}
<input type="submit" value="Save" />
I have two models like below.
public class Bill
{
public int Id { get; set; }
public string InvoiceNumber { get; set; }
public Int64 Amount { get; set; }
public int? NewPaymentId { get; set; }
public virtual NewPayment RelPayment { get; set; }
}
public class NewPayment
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LstName { get; set; }
public DateTime PaymentDate { get; set; }
public Int64 ProvisionNumber { get; set; }
public Int64 CreditCardNumber { get; set; }
public int ExpMonth { get; set; }
public int ExpYear { get; set; }
public int Cv2 { get; set; }
public Int64 Amount { get; set; }
public string UserId { get; set; }
public string CustomerNote { get; set; }
}
Customer is going to pay his invoices via credit card in my application.
I had one view which i posted the NewPayment model to the action. But now, i need to send also which invoices will be paid. So i need to create one more form for the Bill model i think ? But i cant figure out how can i pass two model to same action and i dont know the NewPaymentId before executing the payment method.
REGARDING TO THE COMMENTS :
My combine model as below :
public class Payment
{
public IEnumerable<Bill> Bill { get; set; }
public NewPayment NewPayment { get; set; }
}
And my view as below :
#model IEnumerable<ModulericaV1.Models.Bill>
<form class="form-no-horizontal-spacing" id="NewPayment" action="/NewPayment/AddInvoice" method="post">
<div class="row column-seperation">
<div class="col-md-6">
<h4>Kart Bilgileri</h4>
<div class="row form-row">
<div class="col-md-5">
<input name="FirstName" id="FirstName" type="text" class="form-control" placeholder="Kart Üzerindeki Ad">
</div>
<div class="col-md-7">
<input name="LastName" id="LastName" type="text" class="form-control" placeholder="Kart Üzerindeki Soyad">
</div>
</div>
<div class="row form-row">
<div class="col-md-12">
<input name="CreditCardNumber" id="CreditCardNumber" type="text" class="form-control" placeholder="Kart Numarası">
</div>
</div>
<div class="row form-row">
<div class="col-md-5">
<input name="ExpYear" id="ExpYear" type="text" class="form-control" placeholder="Son Kullanma Yıl (20..)">
</div>
<div class="col-md-7">
<input name="ExpMonth" id="ExpMonth" type="text" class="form-control" placeholder="Son Kullanma Ay (1-12)">
</div>
</div>
<div class="row form-row">
<div class="col-md-5">
<input name="Cv2" id="Cv2" type="text" class="form-control" placeholder="Cv2">
</div>
<div class="col-md-7">
<input name="Amount" id="Amount" type="text" class="form-control" placeholder="Miktar TL ">
</div>
</div>
<div id="container">
<input id="Interests_0__Id" type="hidden" value="" class="iHidden" name="Interests[0].Id"><input type="text" id="InvoiceNumber_0__InvoiceNumber" name="[0].InvoiceNumber"><input type="text" id="Interests_0__InterestText" name="[0].Amount"> <br><input id="Interests_1__Id" type="hidden" value="" class="iHidden" name="Interests[1].Id"><input type="text" id="InvoiceNumber_1__InvoiceNumber" name="[1].InvoiceNumber"><input type="text" id="Interests_1__InterestText" name="[1].Amount"> <br>
</div>
<input type="button" id="btnAdd" value="Add New Item" />
<button class="btn btn-danger btn-cons" type="submit"> Ödemeyi Gerçekleştir</button>
</form>
</div>
</div>
In my controller, i am getting payment model as null.
public ActionResult AddInvoice(Payment payment) {
foreach (var item in payment.Bill)
{
var Billing = new Bill();
Billing.Amount = item.Amount;
Billing.InvoiceNumber = item.InvoiceNumber;
db.Bill.Add(Billing);
db.SaveChanges();
}
return View();
}
}
i complete Marko with an example
public class CombineModel
{
public Bill Bill{ get; set; }
public NewPayment NewPayment{ get; set; }
}
You appear to already have the solution in your model. Your bill object can hold a reference to a related new payment. You can either lazy read the new payment from database or you could assign a new newpayment object to the bill before sending to the view.
View models are good practice, but you might be happy levering the model you have naturally as I just described.
Update
Sorry, this should be:
The other way around - Pass in NewPayment
Add public IEnumarable<Bill> Bills {get; set;} to NewPayment model
And that way, you can access the Bills associated with the given payment.
Code first stuff:
You should decorate Bill's RelPayment with [ForeignKey("NewPaymentID"], so EF (I assume you are using Entity Framework), knows how to wire up the relationship.
You will also likely need to add the following Bills = new List<Bill>(); into a NewPayment constructor.
If you don't like Zakos Solution you can make tuple :
var tuple= new Tuple<Bill,NewPayment>(obj1,obj2);
And in view you will have :
#model Tuple<Bill,NewPayment>
But you should use #Zakos solution.
So you can use ViewModel, take this ViewModel:
public class PaymentBillViewModel
{
public int BillId { get; set; }
public int PaymentId { get; set; }
public string InvoiceNumber { get; set; }
public Int64 Amount { get; set; }
public int? NewPaymentId { get; set; }
public virtual NewPayment RelPayment { get; set; }
public int Id { get; set; }
public string FirstName { get; set; }
public string LstName { get; set; }
public DateTime PaymentDate { get; set; }
public Int64 ProvisionNumber { get; set; }
public Int64 CreditCardNumber { get; set; }
public int ExpMonth { get; set; }
public int ExpYear { get; set; }
public int Cv2 { get; set; }
public Int64 Amount { get; set; }
public string UserId { get; set; }
public string CustomerNote { get; set; }
}
actually put what you need in your View. then in the post action cast the ViewModel to the related Model:
[HttpPost]
public ActionResult Sample(PaymentBillViewModel model)
{
if (ModelState.IsValid)
{
var obj=new NewPayment
{
LstName= model.LstName,
Amount=model.Amount,
//... cast what else you need
}
}
return View();
}
you can use Automapper on casting, for more info about using Automapper take a look at this article.