Id always invalid - c#

I made a Blog page and I wanted to add comments to my blog page. I created a model and controller named BlogComment and I opened a Create action form belonging to BlogComment on my Blog page.
I get RefId invalid and attempt value = "" when I post the form, I would appreciate it if you could help.
This is my HTML markup:
<form asp-area="onepoint" asp-controller="BlogComments" asp-action="Create">
<div hidden>
<input name="RefId" id="RefId" type="number" hidden>
<input name="BlogId" id="BlogId" type="number" hidden>
<input name="BlogCommentApproved" id="BlogCommentApproved" type="checkbox" value="true" hidden>
<input name="BlogCommentApprovedById" id="BlogCommentApprovedById" type="number" hidden>
<input name="BlogCommentApproveDate" id="BlogCommentApproveDate" type="datetime" hidden>
<input name="CommentCreateDate" id="CommentCreateDate" type="datetime" hidden>
</div>
<div class="row">
<div class="col-md-9">
<div class="form-group">
<textarea class="form-control" name="CommentContent" id="CommentContent" rows="5" placeholder="Yorumunuz..."></textarea>
</div>
<div class="row">
<div class="col-md-4">
<input class="form-control" name="Fullname" id="Fullname" type="text" placeholder="Ad Soyad">
</div>
<div class="col-md-4">
<input class="form-control" name="Email" id="Email" type="text" placeholder="E-Posta">
</div>
<div class="col-md-4">
<input id="SendFeedbackBlog" onclick="SendMessage()" type="submit" class="button-62" value="#localizer["Yorum Gönder"]" style="float:right">
</div>
</div>
</div>
<div class="col-md-3"></div>
</div>
</form>
This is my BlogComment class:
/// <summary>
/// Referans Numarası
/// </summary>
[Key]
[Column(TypeName = "int")]
public int RefId { get; set; }
/// <summary>
/// Blog Id
/// </summary>
public int? BlogId { get; set; }
[ForeignKey("BlogId")]
public virtual Blog Blog { get; set; }
/// <summary>
/// Blog Yorumu Onayla
/// </summary>
public bool BlogCommentApproved { get; set; }
/// <summary>
/// Yorumu Onaylayan Kullanıcı Id'si
/// </summary>
public int? BlogCommentApprovedById { get; set; }
[ForeignKey("BlogApprovedById")]
public virtual User ApprovedBy { get; set; }
/// <summary>
/// Blog Yorumu Onay Tarihi
/// </summary>
public DateTime? BlogCommentApproveDate { get; set; }
/// <summary>
/// Yorumun Yazıldığı Tarih
/// </summary>
public DateTime? CommentCreateDate { get; set; }
/// <summary>
/// Yorum Yazanın İsim ve Soyismi
/// </summary>
public string Fullname { get; set; }
/// <summary>
/// Yorum Yazanın E-mail Adresi
/// </summary>
public string Email { get; set; }
/// <summary>
/// Yazılan Yorum
/// </summary>
public string CommentContent { get; set; }
And this is my BlogCommentController:
public async Task<IActionResult> Create([Bind("RefId,BlogId,BlogCommentApproved,BlogCommentApprovedById,BlogCommentApproveDate,CommentCreateDate,Fullname,Email,CommentContent")] BlogComment blogComment)
{
if (ModelState.IsValid)
{
_context.Add(blogComment);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["BlogId"] = new SelectList(_context.Blogs, "RefId", "RefId", blogComment.BlogId);
return View(blogComment);
}

I tried with your codes and got the ModelState error:
Then I setted the input box with a default value 0
<input name="RefId" id="RefId" type="number" value="0" hidden>
the error disappeared
It seems a ModelBidng error
If you still got the same ModelState error,this document may help

Related

ASP.NET MVC User ID Link with other Tables

I am working on a Data Entry system for storing users financial data. Each user will enter his Revenues and Expenses each in a table.
The tables were designed as follows:
Primary Key: Rev/Exp ID
Foreign Key: Organization ID
This is a sample for my models:
public class Revenue
{
[Key]
public int RevenueId { get; set; }
public int Year { get; set; }
public double Source1 { get; set; } = 0;
public double Source2 { get; set; } = 0;
public double Source3 { get; set; } = 0;
public double Source4 { get; set; } = 0;
// Foreign Key Relationship
public string OrganizationId{ get; set; }
public virtual Organization Organization{ get; set; }
}
public class Organization
{
public virtual ICollection<Revenue> Revenues { get; set; }
public virtual ICollection<Expense> Expenses { get; set; }
}
This is the DBContext:
public class AppDbContext : IdentityDbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
// Create tables in DB
public DbSet<Organization > Organization { get; set; }
public DbSet<Revenue> Revenue { get; set; }
public DbSet<Expense> Expense { get; set; }
}
Here is the Create Action in the Controller:
// GET: Revenue/Create
public IActionResult Create()
{
return View();
}
// POST: Revenue/Create
// To protect from overposting attacks, 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<IActionResult> Create([Bind("RevenueId,Year,Source1,Source2,...,OrganizationId")] Revenue revenue)
{
if (ModelState.IsValid)
{
_context.Add(revenue);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["OrganizationId"] = new SelectList(_context.OrganizationId, "Id", "Id", revenue.OrganizationId);
return View(revenue);
}
Finally, Create View:
#using Microsoft.AspNetCore.Identity
#inject SignInManager<IdentityUser> SignInManager
#inject UserManager<IdentityUser> UserManager
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Revenue</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="Year" class="control-label"></label>
<input asp-for="Year" class="form-control" />
<span asp-validation-for="Year" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Source1" class="control-label"></label>
<input asp-for="Source1" class="form-control" />
<span asp-validation-for="Source1" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Source2" class="control-label"></label>
<input asp-for="Source2" class="form-control" />
<span asp-validation-for="Source2" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Source3" class="control-label"></label>
<input asp-for="Source3" class="form-control" />
<span asp-validation-for="Source3" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Source4" class="control-label"></label>
<input asp-for="Source4" class="form-control" />
<span asp-validation-for="Source4" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrganizationId" class="control-label"></label>
<input asp-for="OrganizationId" class="form-control" value="#UserManager.GetUserId(User)"/>
<span asp-validation-for="OrganizationId" class="text-danger"></span>
</div>
</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");}
}
So, after a lot of search I was able to capture user ID with UserManager and assigning it to a hidden field, then sending it with the form. However, that did not work, the form is not submitting and no error messages are displayed neither.
Is this is a correct way of capturing user ID as a Foreign Key and how to fix the Create Action ?
You didn't really specify anything about your authentication. If you are using typical ASP.Net authentication, you can probably use User.Identity.Name, like this:
if (ModelState.IsValid)
{
revenue.UserId = User.Identity.Name
_context.Add(revenue);
...
As from .NET 6, in order to assign an attribute in a model to be Nullable the ? should be added after the name of the attribute, otherwise it is required.
The problem was that the UserId is passed but the User object is null (which should be because it is just a reference).
So the model should be:
public class Revenue
{
[Key]
public int RevenueId { get; set; }
public int Year { get; set; }
public double Source1 { get; set; } = 0;
public double Source2 { get; set; } = 0;
public double Source3 { get; set; } = 0;
public double Source4 { get; set; } = 0;
// Foreign Key Relationship
public string OrganizationId{ get; set; }
public Organization? Organization{ get; set; }
}
And the view will be as is by passing user ID in a hidden field that we got from UserManager.

Why does my List of Objects rendered as Checkboxes return an Empty List? [ASP.NET Core - 3.1]

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; }
}

How to save user data to List in ASP.Net Core

We need to register a new training course in the system. Save the Course Name, Course Price and Lesson List into the database. The number of lessons for each course is different, so the user will dynamically add fields to enter the name of each lesson. How to get the data entered by the user from the fields and save them to the list, and subsequently to the database?
public class RegisterCourseViewModel
{
public string Name { get; set; }
public decimal Price { get; set; }
public List<Lesson> ListOfLessons { get; set; }
}
public class Lesson
{
public int LessonId { get; set; }
public string Name { get; set; }
}
#model RegisterCourseViewModel
<div>
<h2>Registration a new course</h2>
<form asp-area="Staff" asp-controller="Course" asp-action="AddCourse" method="post">
<div asp-validation-summary="All"></div>
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
</div>
<div>
<label asp-for="Price"></label>
<input asp-for="Price" />
<span asp-validation-for="Price"></span>
</div>
<div ID="items">
Lesson 1:
<input type="text" name="item1" size="45"><br>
<input type="button" value="Add a new lesson" onClick="AddItem();" ID="add">
<input type="button" value="Delete the lesson" onClick="DeleteItem();" ID="delete">
</div>
<div>
<input type="submit" value="Registration" />
</div>
</form>
</div>
From this code:
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
</div>
<div>
<label asp-for="Price"></label>
<input asp-for="Price" />
<span asp-validation-for="Price"></span>
</div>
I get Name and Price in my controller method and save it to DB. But how can I get a list of user-entered lessons names?
This is controller's method:
public IActionResult AddCourse(RegisterCourseViewModel model)
{
if (ModelState.IsValid)
{
CourseModel newCourse = new CourseModel
{
Name = model.Name,
Price = model.Price,
ListOfLessons = model.ListOfLessons <---- How to get this List?
};
courseModel.SaveCourse(newCourse);
return RedirectToAction("Index", "Home", new { area = "Staff" });
}
return View(model);
}
public class CourseModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public List<Lesson> ListOfLessons { get; set; }
}
Here is a working demo:
View:
#model RegisterCourseViewModel
<div>
<h2>Registration a new course</h2>
<form asp-area="Staff" asp-controller="Course" asp-action="AddCourse" method="post">
<div asp-validation-summary="All"></div>
//...
<div ID="items">
Lesson 1:
//change the name here...
<input type="text" name="ListOfLessons[0].Name"size="45"><br>
<input type="button" value="Add a new lesson" onClick="AddItem();" ID="add">
<input type="button" value="Delete the lesson" onClick="DeleteItem();" ID="delete">
</div>
<div>
<input type="submit" value="Registration" />
</div>
</form>
</div>
#section Scripts
{
<script>
function AddItem() {
var index = $('input[name^="ListOfLessons"]').length;
$("#add").before('<input type="text" size="45" name="ListOfLessons[' + index + '].Name" /><br>')
}
</script>
}
Result:
By Converting course list into Json string, and then using one column of table in database to save it, you can get user's dynamical course list.
So use database model like:
public class RegisterCourse
{
public string Name { get; set; }
public decimal Price { get; set; }
public string ListOfLessons { get; set; }
}
Use JsonConvert.SerializeObject(courseList) to convert user inputed courses and then insert it to database.
And JsonConvert.DeserializeObject<Class>(jsonstr) to read user's course List from database model

Populating a PartialView's model with content from the Parent page's model in ASP.NET MVC

I am trying to figure out how to populate the Model of my Partial View. For example the PartialView model includes everything the user enters in a notes dialog such as Subject and NoteContent, but it additionally needs the Unique Id of the Model from the parent page which is a Product Id. This way when the note is saved from the dialog window I can save it for that specific product.
In the below example if the user is on the ParentPage viewing a Product with Id 12 and wants to add a note they would click the Notes button to open the dialog window, fill out a subject and content and hit submit. During this submission to the controller EntityModule should = "Product" and EntityKey should = 12 if the ProductId is 12. I am trying to figure out how the NoteViewModel will retrieve these two fields from the parent ViewModel.
ProductViewModel.cshtml
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
NoteViewModel.cshtml
public int Id { get; set; }
public string EntityModule { get; set; }
public int EntityKey { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
ParentPage.cshtml
#model MyApp.Web.ViewModels.Shared.ProductViewModel
#{ await Html.RenderPartialAsync("_NotesPartial"); }
_NotesPartial.cshtml
#model MyApp.Web.ViewModels.Shared.NoteViewModel
<button id="open" class="btn btn-primary">Notes</button>
#(Html.Kendo().Window()
.Name("window")
.Title("About Alvar Aalto")
.Visible(false)
.Draggable()
.Resizable()
.Width(600)
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
.Content(#<text>
<form asp-action="_NotesPartial">
<div class="form-horizontal">
<h4>NoteViewModel</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Subject" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Subject" class="form-control" />
<span asp-validation-for="Subject" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Content" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="Content" class="form-control" cols="40" rows="4"></textarea><span asp-validation-for="Content" 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>
</form>
</text>)
)
<script>
$("#open").click(function () {
var win = $("#window").data("kendoWindow");
win.center();
win.open();
});
</script>
One of the ways is to fill and pass the model through the parent page. For example:
public class ProductViewModel {
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public NoteViewModel Note { get; set;}
}
Then, use something like this:
#{ await Html.RenderPartialAsync("_NotesPartial", Model.Note); }
There is no RenderAction in MVC6, which was a good solution for such purposes:
Html.RenderAction("_NotesPartial", new { id = ProductViewModel.Id })
but still you can use it in MVC5.

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