Asp.net mvc razor with validate.unobtrusive - asp.net-mvc-3

Model----------------------
public class Test
{
[Required(ErrorMessage = "Must Be Select ")]
public string TestList { get; set; }
}
Controller-----------------
public ActionResult Index(){
Test test = new Test();
string code = "11";
Dictionary<string, string> selectList = new Dictionary<string, string>();
selectList.Add("33", "33 value");
selectList.Add("22", "22 value");
selectList.Add("11", "11 value");
ViewBag.TestList = selectList.Select(x => new SelectListItem {
Text = x.Value, Value = x.Key, Selected = x.Key.Equals(code)
}).ToList();
return View(test);
}
View-----------------------
#model ~~~
#Html.DropDownListFor(model => model.TestList, null, "--SelectThis--")
i use c#, mvc3, razor with jquery.unobtrusive
that code are cool
but has problem -- html source view
<select name="TestList" id="TestList"></select>
<select name="TestList" id="TestList" data-val=true data-val-required="Must Be Select">
i want second result..
how can i do??

If you want the second result ensure that this #Html.DropDownListFor helper is inside a form:
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.Code, null, "--SelectThis--")
<input type="submit" value="OK" />
}
Also passing null as second argument is unlikely something that will work. You probably meant:
#using (Html.BeginForm())
{
#Html.DropDownListFor(
model => model.Code,
new SelectList(ViewBag.TestList, "Value", "Text"),
"--SelectThis--"
)
<input type="submit" value="OK" />
}
and what I would strongly recommend you is the following:
Model:
public class Test
{
[Required(ErrorMessage = "Must Be Select ")]
public string TestList { get; set; }
public IEnumerable<SelectListItem> TestList { get; set; }
}
Controller:
public ActionResult Index()
{
var selectList = new Dictionary<string, string>
{
{ "33", "33 value" },
{ "22", "22 value" },
{ "11", "11 value" },
};
var model = new Test
{
Code = "11",
TestList = selectList.Select(x => new SelectListItem
{
Text = x.Value, Value = x.Key
})
};
return View(model);
}
View:
#using (Html.BeginForm())
{
#Html.DropDownListFor(
model => model.Code,
new SelectList(Model.TestList, "Value", "Text"),
"--SelectThis--"
)
<input type="submit" value="OK" />
}

Related

Selected Dropdown value is not inserted into database but textbox value does

Here what I have tried to achieve is that a region has many zones so that zone is populated from a database then a user inserts the name of the region in the textbox then he selects different zones from the dropdown list the selected zone value should keep once selected and clicks the submit button. When the submit button has clicked the name of the region is inserted into the database but the selected dropdown list value is not inserted. here is the code that I have tried
the region controller
// GET: Regions
public ActionResult Index()
{
var regions = db.Regions.Include(r => r.Zone);
return View(regions.ToList());
}
// GET: Regions/Create
public ActionResult Create()
{
Regions zones = new Regions();
zones.regioness = PopulateZones();
ViewBag.ZoneID = new SelectList(db.Zones, "ZoneID", "ZoneName");
return View(zones);
}
public List<SelectListItem> PopulateZones()
{
List<SelectListItem> zones = new List<SelectListItem>();
string conString = ConfigurationManager.ConnectionStrings["StoreContext"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT ID, ZoneName FROM Zones", con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
fruits.Add(new SelectListItem
{
Text = sdr["ZoneName"].ToString(),
Value = sdr["ID"].ToString()
});
}
}
con.Close();
}
}
return zones;
}
[HttpPost]
public ActionResult Create([Bind(Include = "ID,RegionName")] Regions reg)
{
reg.regioness = PopulateZones();
foreach (SelectListItem item in reg.regioness)
{
if (item.Value == reg.ID.ToString())
{
item.Selected = true;
db.Regions.Add(reg);
db.SaveChanges();
break;
}
}
return View(reg);
}
And my Region model is
public class Regions
{
public int ID { get; set; }
public string RegionName { get; set; }
[NotMapped]
public List<SelectListItem> regioness { get; set; }
public int? ZoneID { get; set; }
public virtual Zones Zone { get; set; }
}
and Zone model class
public class Zones
{
[Key]
public int ID { get; set; }
public string ZoneName { get; set; }
public virtual ICollection<Regions> Regions { get; set; }
}
and my create view in region
#model RegionAndZones.Models.Regions
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Regions</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.RegionName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RegionName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RegionName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ZoneID, "ZoneID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownList("ZoneID", null, htmlAttributes: new { #class = "form-control" })*#
#Html.ValidationMessageFor(model => model.ZoneID, "", new { #class = "text-danger" })
#Html.DropDownListFor(m => m.ID, new SelectList(Model.regioness, "Value", "Text"), "Please select")
</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>
is there any one who can help me any help would be appreciated

Many to Many Relation Popup

basically from embedded field and new to MVC/ASP.net, learning.
I have 2 entities with Many to Many relation.
It is working fine i am able to assign relation bet
Heading
ween them using checkbox.
I want to implement the following:
On Create page of Entity 1, Relative Entity 2 list is shown in table with Link and Unlink buttons.
Find below Image:
Link button will open up the popup which will show Entity 2 listing which is not there in the relation with the Entity 1.
User will select the required Entity 2 using checkbox and press 'Submit button.
On pressing Submit button, the selected Entity 2 objects are added to the **Entity 2 ** table in the Create view and popup closes.
On Saving create view will save everything with relation.
I hope I'm not asking too much... Not able to judge.
Thanks in advance.
Already Working:
1) I am able to open the model using bootstrap modal popup approach and pass the Entity 2 list to it.
2.) I am able to display the list in table.
To achieve:
1) Populate Entity 2 list in popup view with objects which are not in the Entity 2 table in the main view.
2) Have Checkbox in Popup table for selection.
3) Get the selected Entity 2 row details to main view without posting to controller.
4) Update Entity 2 table in the main view with the selected rows.
5) Save to table when save button is pressed..
Entity 1:
public partial class JobPost
{
public JobPost()
{
this.JobTags = new HashSet<JobTag>();
}
public int JobPostId { get; set; }
public string Title { get; set; }
public virtual ICollection<JobTag> JobTags { get; set; }
}
Entity 2:
public partial class JobTag
{
public JobTag()
{
this.JobPosts = new HashSet<JobPost>();
}
public int JobTagId { get; set; }
public string Tag { get; set; }
public virtual ICollection<JobPost> JobPosts { get; set; }
}
public class TempJobTag
{
public int JobTagId { get; set; }
public string Tag { get; set; }
public bool isSelected { get; set; }
}
View Model:
public class JobPostViewModel
{
public JobPost JobPost { get; set; }
public IEnumerable<SelectListItem> AllJobTags { get; set; }
private List<int> _selectedJobTags;
public List<int> SelectedJobTags
{
get
{
if (_selectedJobTags == null)
{
_selectedJobTags = JobPost.JobTags.Select(m => m.JobTagId).ToList();
}
return _selectedJobTags;
}
set { _selectedJobTags = value; }
}
}
Entity 1 Controller:
// GET: JobPosts/Create
public ActionResult Create()
{
var jobPostViewModel = new JobPostViewModel
{
JobPost = new JobPost(),
};
if (jobPostViewModel.JobPost == null)
return HttpNotFound();
var allJobTagsList = db.JobTags.ToList();
jobPostViewModel.AllJobTags = allJobTagsList.Select(o => new SelectListItem
{
Text = o.Tag,
Value = o.JobTagId.ToString()
});
return View(jobPostViewModel);
}
// POST: JobPosts/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 ActionResult Create(JobPostViewModel jobpostView)
{
if (ModelState.IsValid)
{
var newJobTags = db.JobTags.Where(
m => jobpostView.SelectedJobTags.Contains(m.JobTagId)).ToList();
var updatedJobTags = new HashSet<int>(jobpostView.SelectedJobTags);
foreach (JobTag jobTag in db.JobTags)
{
if (!updatedJobTags.Contains(jobTag.JobTagId))
{
jobpostView.JobPost.JobTags.Remove(jobTag);
}
else
{
jobpostView.JobPost.JobTags.Add((jobTag));
}
}
db.JobPosts.Add(jobpostView.JobPost);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(jobpostView);
}
public ActionResult ViewJobPostTagPopUp()
{
var allJobTagsList = db.JobTags.ToList();
foreach (JobTag jobTag in db.JobTags)
{
if (jobTag.JobTagId == 1)
{
allJobTagsList.Remove(jobTag);
}
}
List<TempJobTag> tmpJobTags = new List<TempJobTag>();
foreach (JobTag jobTag in db.JobTags)
{
TempJobTag tmpJT = new TempJobTag();
tmpJT.Tag = jobTag.Tag;
tmpJT.JobTagId = jobTag.JobTagId;
tmpJobTags.Add(tmpJT);
}
return PartialView("JobTagIndex", tmpJobTags);
}
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult ViewJobPostTagPopUp(List<TempJobTag> data)
{
if (ModelState.IsValid)
{
}
return Json(new { success = true, message = "Some message" });
}
Main View:
#model MVCApp20.ViewModels.JobPostViewModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>JobPost</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.JobPost.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.JobPost.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.JobPost.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AllJobTags, "JobTag", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(m => m.SelectedJobTags, Model.AllJobTags)
</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("+", "ViewJobPostTagPopUp", "JobPosts",
null, new { #class = "modal-link btn btn-success" })
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Partial Popup View:
#model IEnumerable<MVCApp20.Models.TempJobTag>
#{
ViewBag.Title = "Index";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Tags</h2>
#using (Html.BeginForm())
{
<table id="datatable" class="table">
<tr>
<th>
<input type="checkbox" id="checkAll" />
</th>
<th>
#Html.DisplayNameFor(model => model.Tag)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#*#Html.EditorFor(modelItem => item.isSelected)*#
<input type="checkbox" class="checkBox"
value="#item.isSelected" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Tag)
</td>
</tr>
}
</table>
#*<div>
#Html.ActionLink("Done", "ViewJobPostTagPopUp", "JobPosts",
null, new { #class = "modal-link btn btn-primary" })
</div>*#
<div>
<button type="submit" id="btnSubmit" class=" btn btn-primary">Submit</button>
</div>
}
<script>
$(document).ready(function () {
$("#checkAll").click(function () {
$(".checkBox").prop('checked',
$(this).prop('checked'));
});
});
$(function () {
$('#btnSubmit').click(function () {
var sdata = new Array();
sdata = getSelectedIDs();
var postData = {};
postData[values] = sdata;
$.ajax({
url: '#Url.Action("ViewJobPostTagPopUp")',
type: "POST",
type: this.method,
//data: $(this).serialize(),
data: JSON.stringify(product),
success: function (result) {
alert("success");
},
fail: function (result) {
alert("fail");
}
});
//alert("hiding");
//$('#modal-container').modal('hide');
});
});
function getSelectedIDs() {
var selectedIDs = new Array();
var i = 0;
$('input:checkbox.checkBox').each(function () {
if ($(this).prop('checked')) {
selectedIDs.push($(this).val());
i++;
alert("got" + i);
}
});
return selectedIDs;
}
</script>

View to Controller in mvc3

I have a problem on passing values from view to controller
Here is my view:
#model IEnumerable<SQLOperation.Models.QuestionClass.Tabelfields>
#{
ViewBag.Title = "Question";
}
<h3> Question</h3>
#{int i = 0;}
#foreach (var item in Model)
{
using (Html.BeginForm("Question", "Home"))
{
#Html.DisplayFor(modelItem => item.QuestionName)
#Html.HiddenFor(m => item.QuestionID)
<br /><br />
if (item.Option1 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option1, item)
#Html.DisplayFor(modelItem => item.Option1)
<br /><br />
}
if (item.Option2 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option2, item)
#Html.DisplayFor(modelItem => item.Option2)
<br /><br />
}
if (item.Option3 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option3, item)
#Html.DisplayFor(modelItem => item.Option3)
<br /><br />
}
if (item.Option4 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option4, item)
#Html.DisplayFor(modelItem => item.Option4)
<br /><br />
}
i = (Int16)i + 1;
if (Model.Count() == i)
{
<input name="btnsumbit" type="submit" value="Submit Feedback"
style="font-family:Segoe UI Light;font-size:medium;"/>
}
}
}
My controller :
[HttpGet]
public ActionResult Question(string email)
{
var tf = new QuestionClass.Tabelfields();
IList<QuestionClass.Tabelfields> viewmodel = new List<QuestionClass.Tabelfields>();
var q = QuestionClass.getallQuestion(email).ToList();
foreach (SQLOperation.Models.Question item in q)
{
QuestionClass.Tabelfields viewItem = new QuestionClass.Tabelfields();
viewItem.Email = item.Email;
viewItem.QuestionID = item.QuestionID;
viewItem.QuestionName = item.QuestionName;
viewItem.Option1 = item.Option1;
viewItem.Option2 = item.Option2;
viewItem.Option3 = item.Option3;
viewItem.Option4 = item.Option4;
viewmodel.Add(viewItem);
}
return View(viewmodel);
}
[HttpPost, ActionName("Question")]
public void Question(IEnumerable<QuestionClass.Tabelfields> items)
{
}
My Model:
public class QuestionClass
{
public static FeedbackDatabaseDataContext context = new FeedbackDatabaseDataContext();
public class Tabelfields : Question
{
//public decimal QuestionID { get; set; }
//public string Email { get; set; }
//public string QuestionName { get; set; }
//public string Option1 { get; set; }
//public string Option2 { get; set; }
//public string Option3 { get; set; }
//public string Option4 { get; set; }
public string SelectedOption { get; set; }
}
public static List<Question> getallQuestion(string email)
{
var list = (from q in context.Questions where q.Email == #email select q);
return list.ToList();
}
}
however I get NULL in "items" in controller.
[HttpPost, ActionName("Question")]
public void Question(IEnumerable<QuestionClass.Tabelfields> items)
{
}
Whereas if I change my View & Controller to below , I get last value from database in controller
View:
#foreach (var item in Model)
{
using (Html.BeginForm("Question", "home", new { email=item.Email, q=item.QuestionID}))
{
#Html.DisplayFor(modelItem => item.QuestionName)
#Html.HiddenFor(m => item.QuestionID)
.
.
.
.
}
}
Controller:
[HttpPost, ActionName("Question")]
public void Question(string email,int q)
{
}
I get values in email and q
so how can I get all values i.e. QuestionId,Email,Questionname and it's appropriate selected value (radiobutton) in controller ?
i.e. in Following Controller:
[HttpPost, ActionName("Question")]
public void Question(IEnumerable<QuestionClass.Tabelfields> items)
{
}
You need to index the Html.*For items as such;
#Html.RadioButtonFor(m => m[i].SelectedOption, item.Option3, item)
To make things simplier, i'd probably get rid of the foreach & and separate i declaration and use the following;
#for(int i=0; i < Model.Count; i++)
{
#Html.HiddenFor(m => m[i].QuestionID)
#Html.RadioButtonFor(m => m[i].SelectedOption, Model[i].Option3, Model[i])
}
etc.
Indexing like this will cause the html to be rendered with the indexing intact:
<input type='hidden' name=[0].'QuestionId' />
<input type='hidden' name=[1].'QuestionId' />
<input type='hidden' name=[2].'QuestionId' />
Rather than what you're doing currently, which ends up rendering as so;
<input type='hidden' name='QuestionId' />
<input type='hidden' name='QuestionId' />
<input type='hidden' name='QuestionId' />
Without the indexing, each form field is given the same name, so you're controller is going to think only one was returned.

Posting model data from one View to another in mvc3 using ajx

I want to transfer model data from one View to another View (in a dialog) using Ajax.Actionlink were i am getting null values on Post Action
This is my View
#using (Ajax.BeginForm("", new AjaxOptions { }))
{
for (int i = 0; i < Model.city.Count; i++)
{
<div class="editor">
<p>
#Html.CheckBoxFor(model => model.city[i].IsSelected, new { id = "check-box-1" })
#Html.HiddenFor(model => model.city[i].Id)
#Ajax.ActionLink(Model.city[i].Name, "PopUp", "Home",
new
{
#class = "openDialog",
data_dialog_id = "emailDialog",
data_dialog_title = "Cities List",
},
new AjaxOptions
{
HttpMethod = "POST"
})
#Html.HiddenFor(model => model.city[i].Name)
</p>
</div>
}
}
On using Ajax.Actionlink i am creating a dialog using ajax scripting
My controller class for this View is
public ActionResult Data()
{
var cities = new City[] {
new City { Id = 1, Name = "Mexico" ,IsSelected=true},
new City { Id = 2, Name = "NewJersey",IsSelected=true },
new City { Id = 3, Name = "Washington" },
new City { Id = 4, Name = "IIlinois" },
new City { Id = 5, Name = "Iton" ,IsSelected=true}
};
var model = new Citylist { city = cities.ToList() };
//this.Session["citylist"] = model;
return PartialView(model);
}
another View for displaying Post action data is
#model AjaxFormApp.Models.Citylist
#{
ViewBag.Title = "PopUp";
}
<h2>
PopUp</h2>
<script type="text/javascript">
$(function () {
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
var checkedAtLeastOne = false;
$('input[id="check-box-2"]').each(function () {
if ($(this).is(":checked")) {
checkedAtLeastOne = true;
// alert(checkedAtLeastOne);
}
});
if (checkedAtLeastOne == true) {
// alert("Test");
$('#div1').show();
$(".dialog").dialog("close");
}
else {
// alert("NotSelected");
$('#div1').hide();
$('#popUp').html(result);
$('#popUp').dialog({
open: function () { $(".ui-dialog-titlebar-close").hide(); },
buttons: {
"OK": function () {
$(this).dialog("close");
}
}
});
}
}
});
return false;
});
});
</script>
<div style="display: none" id="div1">
<h4>
Your selected item is:
</h4>
</div>
#using (Ajax.BeginForm(new AjaxOptions { }))
{
for (int i = 0; i < Model.city.Count; i++)
{
<div class="editor">
<p>
#Html.CheckBoxFor(model => model.city[i].IsSelected,new { id = "check-box-2" })
#Html.HiddenFor(model => model.city[i].Id)
#Html.LabelFor(model => model.city[i].Name, Model.city[i].Name)
#Html.HiddenFor(model => model.city[i].Name)
</p>
</div>
}
<input type="submit" value="OK" id="opener" />
}
#*PopUp for Alert if atleast one checkbox is not checked*#
<div id="popUp">
</div>
and my post controller action result class is
[HttpPost]
public ActionResult PopUp(Citylist model)
{
if (Request.IsAjaxRequest())
{
//var model= this.Session["citylist"];
return PartialView("PopUp",model);
}
return View();
}
My model class is
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class Citylist
{
public IList<City> city { get; set; }
}
You are calling Popup action from actionlink. Instead you should place submit button out of for loop. And give your form right action parameters

MVC3 Binding to collection data model

My question isn't so much about displaying the data its about collecting changes to the data.
My specific scenario is the need to allow users to delete multiple items from a list. I don't know if i'm even approaching this in a locgical way.
The List is a collection of Private Messages. My view model has strings for To, From, Subject, and a bool for "Delete".
public class PrivateMessagesModel {
public PrivateMessagesModel()
{
PrivateMessages = new List<PrivateMessageReceivedModel>();
}
public List<PrivateMessageReceivedModel> PrivateMessages;
}
public class PrivateMessageReceivedModel
{
[DataType(DataType.Text)]
[Display(Name = "From")]
public string From { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Subject")]
public string Subject { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Message")]
public string Message { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Date")]
public DateTime DateTimeSent { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Delete")]
public bool Delete { get; set; }
}
The code to display looks like this. And works ok.
#
model ScaleRailsOnline.Models.PrivateMessagesModel
#{
ViewBag.Title = "Private Messages";
}
<div id="content">
<div class="content">
<h2>
Private Messages</h2>
#using (Html.BeginForm())
{ <table>
#for (int i = 0; i < Model.PrivateMessages.Count; i++)
{
<tr>
<td>
#Html.CheckBoxFor(m => m.PrivateMessages[i].Delete)
</td>
<td>
#Html.DisplayTextFor(m => m.PrivateMessages[i].From)
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Delete" />
</p>
}
</div>
</div>
The problem is when I check a couple of the check boxes and hit the delete button, i get nothing back in the model.
Again, im sure i'm not approaching this in the right way. Any help would be appreciated.
You need to have a controller associated to the Html.BeginForm where the form will be posted.
eg
<div id="formid">
#using (Html.BeginForm("Index1", "Home", new AjaxOptions { UpdateTargetId = "formid",OnSuccess ="OnSuccess" }, new { id = "TheForm" }))
{
#for (int i = 0; i < Model.PrivateMessages.Count; i++)
{
#Html.CheckBoxFor(m => m.PrivateMessages[i].Delete)
}
<input type="submit" name="name" value="Submit" />
}
</div>
On Controller
public ActionResult Index1(List<PrivateMessageReceivedModel> mod)
{
//Now in the mod you will get the value of the delete checkbox.
}
You have to create a Controller class for your model. Then create method that return ActionResult type. and then create View of the newly created controller method.
Here is a sample code.
Model Class
namespace Mvc3Application1.Models
{
public class PrivateMessage
{
public string From { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
public DateTime DateTimeSent { get; set; }
public bool Delete { get; set; }
}
public class PrivateMessageRepository
{
public List<PrivateMessage> GetPrivateMessages()
{
List<PrivateMessage> myPrivateMessages=new List<PrivateMessage>();
//add list of messages in the object myPrivateMessages
myPrivateMessages.Add(new PrivateMessage { From = "abc#abc.com", Subject = "Subject 1", Message = "Message 1", DateTimeSent = DateTime.Now, Delete = false });
myPrivateMessages.Add(new PrivateMessage { From = "abc1#abc.com", Subject = "Subject 2", Message = "Message 2", DateTimeSent = DateTime.Now, Delete = false });
myPrivateMessages.Add(new PrivateMessage { From = "abc2#abc.com", Subject = "Subject 3", Message = "Message 3", DateTimeSent = DateTime.Now, Delete = false });
myPrivateMessages.Add(new PrivateMessage { From = "abc3#abc.com", Subject = "Subject 4", Message = "Message 4", DateTimeSent = DateTime.Now, Delete = false });
myPrivateMessages.Add(new PrivateMessage { From = "abc4#abc.com", Subject = "Subject 5", Message = "Message 5", DateTimeSent = DateTime.Now, Delete = false });
return myPrivateMessages;
}
}
}
Controller class
namespace Mvc3Application1.Controllers {
public class PrivateMessageController : Controller
{
//
// GET: /PrivateMessage/
// Show all the private messages
public ActionResult ListMessages()
{
return View(new Models.PrivateMessageRepository().GetPrivateMessages());
}
//delete the selected messages and return the collection
[HttpPost]
public ActionResult ListMessages(FormCollection collection)
{
List<Models.PrivateMessage> messages = new Models.PrivateMessageRepository().GetPrivateMessages();//all messages
List<Models.PrivateMessage> cloneMessages = new List<Models.PrivateMessage>();//messages left for deletion
int noOfItems = 0;//no of items deleted
int currentItem = 0;//current item in collection 'messages'
string[] deletedItems = collection[0].Split(',');//return from HTML control collection
for (int i = 0; i < deletedItems.Length; i++)
{
if (bool.Parse(deletedItems[i]) == false)//if checkbox is unchecked
{
cloneMessages.Add(messages[currentItem]);//copy original message in cloneMessages collection
}
else //if checkbox is checked
{
noOfItems++;
i++;
}
currentItem++;
}
ViewBag.Items = noOfItems + " message(s) deleted.";
return View(cloneMessages);
}
} }
View
#model IEnumerable<Mvc3Application1.Models.PrivateMessage>
#{
ViewBag.Title = "Private Messages";
}
<h2>Private Messages</h2>
<div style="color:green;font-weight:bold;">#ViewBag.Items</div>
<br />
#using (Html.BeginForm())
{
<table>
<tr>
<th></th>
<th>
From
</th>
<th>
Subject
</th>
<th>
Message
</th>
<th>
DateTimeSent
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => item.Delete)
</td>
<td>
#Html.DisplayTextFor(modelItem => item.From)
</td>
<td>
#Html.DisplayTextFor(modelItem => item.Subject)
</td>
<td>
#Html.DisplayTextFor(modelItem => item.Message)
</td>
<td>
#Html.DisplayTextFor(modelItem => item.DateTimeSent)
</td>
</tr>
}
</table>
<input type="submit" value="Delete"/>
}

Resources