How can I reload only part of page - asp.net-mvc-3

My page which for online shoping, contains two parts. First part is a list of products.
#model WebUI.Models.CakesListViewModel
#foreach (var p in Model.Cakes) {
Html.RenderPartial("CakesList", p);
}
Each product appears as partial view. CakesList.cshtml
#model Domain.Entities.Cake
<div>
#if (Model.ImageData != null) {
<div style="float:left;margin-right:20px">
<img width="75" height="75" src="#Url.Action("GetImage", "Cake", new { Model.Id })" />
</div>
}
<b>#Model.Name<br />
#Model.Price</b><br />
#Model.Description
#using (Html.BeginForm("AddToCart", "Cart"))
{
#Html.HiddenFor(x => x.Id)
#Html.TextBox("quantity", "", new { style = "width: 20px; text-align: center" })
<input type="image" src="../Images/basket.jpg" />
}
</div>
All page is reloading, after clicking basket image button, but I need to reload only second part of page. How can I do it.
Second part is sum of ordered products.
#model Domain.Entities.Cart
#{
Layout = null;
string str = String.Format("{0}", Model.ComputeTotalValue());
}
<div id="cart">
#Html.ActionLink(str, "Index", "Cart")
</div>
Which is appeared from _Layout.cshtml
</head>
<body>
<div id="header">
#{Html.RenderAction("Summary", "Cart");}
<div class="title">Cakes</div>
</div>
<div id="categories">
#{ Html.RenderAction("Menu", "MenuItems"); }
</div>
<div id="content">
#RenderBody()
</div>
</body>
</html>

//CakeController
namespace WebUI.Controllers
{
public class CakeController : Controller
{
public int PageSize = 4;
private ICakeRepository repository;
public CakeController(ICakeRepository cakeRepository)
{
repository = cakeRepository;
}
public FileContentResult GetImage(int id)
{
Cake prod = repository.Cakes.FirstOrDefault(p => p.Id == id);
if (prod != null)
return File(prod.ImageData, prod.ImageMimeType);
else
return null;
}
public ActionResult OnlineShop(string regions, int page = 1)
{
CakesListViewModel viewModel = new CakesListViewModel
{
Cakes = repository.Cakes
.Where(p => regions == null || p.Name.Trim() == regions),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = 1
},
CurrentCategory = "category"
};
return View("OnlineShop", viewModel);
}
}
}
//OnlineShop.cshtml
#model WebUI.Models.CakesListViewModel
#{
ViewBag.Title = "Cakes";
}
#foreach (var p in Model.Cakes) {
Html.RenderPartial("CakesList", p);
}
//CakesList.cshtml
#model Domain.Entities.Cake
#if (Model.ImageData != null) {
<div style="float:left;margin-right:20px">
<img width="75" height="75" src="#Url.Action("GetImage", "Cake", new { Model.Id })" />
</div>
}
<b>#Model.Name<br />
#Model.Price</b><br />
#Model.Description
#using (Ajax.BeginForm("AddToCart", "Cart", new AjaxOptions { HttpMethod = "Get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "mydiv" }))
{
#Html.HiddenFor(x => x.Id)
#Html.TextBox("quantity", "", new { style = "width: 20px; text-align: center" })
<input type="image" src="../Images/basket.jpg" />
}
//CartController
namespace WebUI.Controllers
{
public class CartController : Controller
{
private ICakeRepository repository;
private IOrderProcessor orderProcessor;
public CartController(ICakeRepository repo, IOrderProcessor proc)
{
repository = repo;
orderProcessor = proc;
}
public ActionResult AddToCart(Cart cart, int id, int quantity = 1)
{
Cake cake = repository.Cakes.FirstOrDefault(p => p.Id == id);
if (cake != null)
cart.AddItem(cake, quantity);
return RedirectToAction("OnlineShop", "Cake");
}
public ActionResult RemoveFromCart(Cart cart, int id)
{
Cake cake = repository.Cakes.FirstOrDefault(p => p.Id == id);
if (cake != null)
cart.RemoveLine(cake);
return RedirectToAction("Index", "Cart");
}
public ViewResult Index(Cart cart, string returnUrl)
{
return View(new CartIndexViewModel
{
Cart = cart,
ReturnUrl = returnUrl
});
}
public ViewResult Summary(Cart cart)
{
return View(cart);
}
}
}
//Summary.cshtml
#model Domain.Entities.Cart
#{
Layout = null;
string str = String.Format("{0}", Model.ComputeTotalValue());
}
<div id="cart">
<p>
<img src="../Images/basket.jpg" />
<div id="mydiv">#Html.ActionLink(str, "Index")</div>
</p>
</div>

<h2>About</h2>
<p>
Put content here.
</p>
#Ajax.ActionLink("Link Text", "ActionThatWillReturnContent", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ContainerThatIWillUpdate"
})
<div id="ContainerThatIWillUpdate"></div>
This will call "ActionThatWillReturnContent" and insert content inside of "ContainerThatIWillUpdate".
Alternative is to use jQuery.ajax which is a lot nicer, but will require a little reading/playing around with.
Update 1:
You send an AJAX request to your action method called AddToCart. This method does some processing and then returns a full view:
return RedirectToAction("OnlineShop", "Cake");
What you want to do, is return a partial view, that will be placed inside of "mydiv", which is your update target id.
Your action method needs to be modified to return PartialView, rather than ActionResult:
public PartialViewResult AddToCart(Cart cart, int id, int quantity = 1)
{
// Inside this action method, you don't want to return a redirect to action,
// you want to return partial view
return PartialView(); // This has three constructors, so you'll need to do a bit of digging.
}

Related

Ajax call always going in error part

I have demo in mvc where I want to fetch user details based on dropdown, i am using ajax for selectedindex changed event of dropdown to show userdetails in partial view, but ajax call is always going in error part..
Controller :-
public ActionResult Index()
{
var usermodel = new UserModel();
usermodel.listuser = GetUserData();
usermodel.UserId = usermodel.listuser.First().UserId;
usermodel.UserName = usermodel.listuser.First().UserName;
usermodel.UserSalary = usermodel.listuser.First().UserSalary;
return View(usermodel);
}
public PartialViewResult GetUserRecord(int UserId)
{
var userModel = new UserModel();
userModel.listuser = GetUserData();
var user = userModel.listuser.Where(e => e.UserId == UserId).FirstOrDefault();
userModel.UserId = user.UserId;
userModel.UserName = user.UserName;
userModel.UserSalary = user.UserSalary;
return PartialView("_UserTestPartial.cshtml", userModel);
}
private List<UserModel> GetUserData()
{
var listuser = new List<UserModel>();
var user1 = new UserModel();
user1.UserId = 1;
user1.UserName = "Abcd";
user1.UserSalary = 25000;
var user2 = new UserModel();
user2.UserId = 2;
user2.UserName = "bcde";
user2.UserSalary = 35000;
var user3 = new UserModel();
user3.UserId = 1;
user3.UserName = "cdef";
user3.UserSalary = 45000;
listuser.Add(user1);
listuser.Add(user2);
listuser.Add(user3);
return listuser;
}
Model:-
public class UserModel
{
public int UserId { get; set; }
public string UserName { get; set; }
public double UserSalary { get; set; }
public List<UserModel> listuser { get; set; }
public IEnumerable < SelectListItem > UserListItems
{
get
{
return new SelectList(listuser, "UserId", "UserName");
}
}
}
Index View:-
#Html.DropDownListFor(m => m.UserId, Model.UserListItems, "---Select User--- ", new { Class = "ddlStyle", id = "ddlUser" })
<div id="partialDiv">
#Html.Partial("_UserTestPartial")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#ddlUser").on("change", function () {
$.ajax(
{
url: '/User/GetUserRecord?UserId=' + $(this).attr("value"),
type: 'GET',
data: " ",
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#partialDiv").html(data);
},
error: function () {
alert("error");
}
});
});
});
</script>
Partial View:-
#model Dropdowndemo.Models.UserModel
<fieldset>
<legend>UserModel</legend>
<div class="display-label">
<strong> #Html.DisplayNameFor(model => model.UserId) </strong>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.UserId)
</div>
<div class="display-label">
<strong> #Html.DisplayNameFor(model => model.UserName) </strong>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.UserName)
</div>
<div class="display-label">
<strong> #Html.DisplayNameFor(model => model.UserSalary) </strong>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.UserSalary)
</div>
</fieldset>
Please remove the data: " ", attribute from ajax, if you're not passing any in it.
In the Index remove
#Html.Partial("_UserTestPartial")
This will throw error since you are not passing any model to the partial view in this way.
As you were binding the partial view via ajax call to #partialDiv it will work fine

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 with ViewModel

I have one ViewModels which contain other ViewModels
public class AllProductsViewModel
{
public ICollection<ProductSearchViewModel> ProductSearch { get; set; }
public ICollection<ProductRentViewModel> ProductRent { get; set; }
public ICollection<ProductBuyViewModel> ProductBuy { get; set; }
}
My Controller is:
public ActionResult Index()
{
var listOfProductsBuy = db.ProductsBuy.Select(x => new ProductBuyViewModel
{
Id = x.Id,
Title = x.Title,
MasterImageUrl = x.Images.FirstOrDefault().Url,
Price = x.Price,
Values = x.Value,
}).ToList();
var listOfProductsRent = db.ProductsRent.Select(y => new ProductRentViewModel
{
Id = y.Id,
Title = y.Title,
MasterImageUrl = y.ImagesRent.FirstOrDefault().Url,
Price = y.Price,
Values = y.Value,
}).ToList();
var listOfProductsSearch = db.ProductSearches.Select(z => new ProductSearchViewModel
{
Id = z.Id,
Title = z.Title,
MasterImageUrl = z.ImagesSearch.FirstOrDefault().Url,
Price = z.Price,
Values = z.Value,
}).ToList();
var viewModel = new AllProductsViewModel { ProductBuy = listOfProductsBuy, ProductRent = listOfProductsRent, ProductSearch = listOfProductsSearch };
return View(viewModel);
}
}
And my View:
#model IEnumerable<RealEstateMarket.ViewModels.AllProductsViewModel>
#{
ViewBag.Title = "Home Page";
}
<br />
<div class="row">
<div class="col-md-3">
#foreach (var item in Model)
{
<h3>#item.ProductBuy.Select(x => x.Title)</h3>
<div>
<img height="100" width="120" class="thumbnail" src="#item.ProductBuy.Select(x => x.MasterImageUrl )" />
</div>
<h3>#item.ProductBuy.Select(x => x.Price) #item.ProductBuy.Select(x => x.Values.Currency)</h3>
}
</div>
</div>
A want to take the fields of ProductBuyViewModel,ProductRentViewModel, ProductSearchViewModel
When I start this code i get the error: The model item passed into the dictionary is of type 'RealEstateMarket.ViewModels.AllProductsViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[RealEstateMarket.ViewModels.AllProductsViewModel]'.
change this
#model IEnumerable<RealEstateMarket.ViewModels.AllProductsViewModel>
to
#model RealEstateMarket.ViewModels.AllProductsViewModel
and then you can access to your list
<div class="col-md-3">
#for (int index=0;index<Model.ProductSearch.Count();index++)
{
<h3>#Model.ProductSearch[index].Title</h3>
<div>
<img height="100" width="120" class="thumbnail" src="#Model.ProductSearch[index].MasterImageUrl )" />
</div>
<h3>#Model.ProductSearch[index].Price #Model.ProductSearch[index].Values.Currency)</h3>
}
</div>

i'm stuck incrementing page variable in infinite scrolling with Ajax.BeginForm

I'm implementing infinite scroll in MVC 5, by Ajax.BeginForm invoking an action returns partial view, i'm struggling in incrementing the page variable it always send 1 to the action !!
Controller
public ActionResult Index()
{
home.Articles = GetArticlesByPage(home.Page);
return View(home);
}
public PartialViewResult NextPageArticles(int page)
{
home.Articles = GetArticlesByPage(page);
return PartialView("~/Views/Home/ArticlePostPartial.cshtml", home.Articles);
}
HomeViewModel
public class HomeViewModel
{
public IEnumerable<ArticleViewModel> _articles;
public IEnumerable<ArticleViewModel> Articles
{
get { return this._articles; }
set
{
this._articles = value;
Page++;
}
}
public int Page { get; set; }
public HomeViewModel()
{
Page = 0;
}
}
View
<div id="MainContainer" class="container-fluid">
#{Html.RenderPartial("ArticlePostPartial", Model.Articles);}
</div>
#using (Ajax.BeginForm("NextPageArticles", "Home", new { page = ??? }, new AjaxOptions
{
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "MainContainer",
LoadingElementId = "imgload",
OnSuccess = "OnSuccessAjax"
}))
{
<input type="submit" id="formbut" class="btn btn-danger hidden" />
}
Something like this should work for you.
<div id="MainContainer" class="container-fluid">
#{Html.RenderPartial("ArticlePostPartial", Model.Articles);}
</div>
#using (Ajax.BeginForm("NextPageArticles", "Home", new { page = Convert.ToInt32(Request.RequestContext.RouteData.Values["page"]) + 1 }, new AjaxOptions
{
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "MainContainer",
LoadingElementId = "imgload",
OnSuccess = "OnSuccessAjax"
}))
{
<input type="submit" id="formbut" class="btn btn-danger hidden" />
}

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

Resources