How to open a View in PopUp in MVC 3 - asp.net-mvc-3

I am using MVC 3, in my project i have 2 view, i want to open 2nd view in 1st View popup
My 1st View is by that i want to Open 2nd View in PopUp,
#model CustomerAddressListModel
#using Nop.Web.Models.Customer;
#{
Layout = "~/Views/Shared/_ColumnsTwo.cshtml";
//title
Html.AddTitleParts(T("PageTitle.Account").Text);
}
<script type="text/javascript">
$(function () {
$('a.dialog').click(function () {
var url = $(this).attr('href');
var dialog = $('<div style="display:none"></div>').appendTo('body');
dialog.load(url, {}, function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog({
close: function (event, ui) {
dialog.remove();
}
});
});
return false;
});
});
</script>
<div class="add-btn-cntrnr left" style="width:400px;">
#Html.ActionLink("AddLink", "AddressAdd", "Customer", new { #class = "dialog" })
</div>
and this is my second view which i want to open in PopUp:
#model CustomerAddressEditModel
#using Nop.Web.Models.Customer;
#{
Layout = null;
}
#using Nop.Web.Framework;
#using (Html.BeginForm())
{
<div class="emai_head">
<span class="emai_head_text">Add Address</span>
#{
var dataDictAddress = new ViewDataDictionary();
//Merge ModelState (required for validation)
dataDictAddress.ModelState.Merge(ViewData.ModelState);
dataDictAddress.TemplateInfo.HtmlFieldPrefix = "Address";
#Html.Partial("_CreateOrUpdateAddress", Model.Address, dataDictAddress)
}
<input type="submit" class="acc_btnn" value=" " />
</div>
}
This is my controller for PopUp view :
[NopHttpsRequirement(SslRequirement.Yes)]
public ActionResult AddressAdd()
{
if (!IsCurrentUserRegistered())
return new HttpUnauthorizedResult();
var customer = _workContext.CurrentCustomer;
var model = new CustomerAddressEditModel();
model.NavigationModel = GetCustomerNavigationModel(customer);
model.NavigationModel.SelectedTab = CustomerNavigationEnum.Addresses;
model.Address = new AddressModel();
//countries
model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries())
model.Address.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString() });
model.Address.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });
return View(model);
}
[HttpPost]
public ActionResult AddressAdd(CustomerAddressEditModel model)
{
if (!IsCurrentUserRegistered())
return new HttpUnauthorizedResult();
var customer = _workContext.CurrentCustomer;
model.NavigationModel = GetCustomerNavigationModel(customer);
model.NavigationModel.SelectedTab = CustomerNavigationEnum.Addresses;
if (ModelState.IsValid)
{
var address = model.Address.ToEntity();
address.CreatedOnUtc = DateTime.UtcNow;
//some validation
if (address.CountryId == 0)
address.CountryId = null;
if (address.StateProvinceId == 0)
address.StateProvinceId = null;
customer.Addresses.Add(address);
_customerService.UpdateCustomer(customer);
// return RedirectToRoute("CustomerAddresses");
}
//If we got this far, something failed, redisplay form
//countries
model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries())
model.Address.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString(), Selected = (c.Id == model.Address.CountryId) });
//states
var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value).ToList() : new List<StateProvince>();
if (states.Count > 0)
{
foreach (var s in states)
model.Address.AvailableStates.Add(new SelectListItem() { Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.Address.StateProvinceId) });
}
else
model.Address.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });
return View(model);
}

Related

MVC ListBox Selected Values

New to MVC and Stackoverflow so sorry for not having enough reputation to post images...
Trying to render a ListBox with pre selected values
My SQL Database:
http://i.imgur.com/bcdXyqE.png
My Entity Framework
http://i.imgur.com/wYWXuAq.png
My Controller
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
var roles = db.Role;
var newList = new List<SelectListItem>();
foreach (var role in roles)
{
newList.Add(
new SelectListItem()
{
Value = role.Id.ToString(),
Text = role.RoleName,
Selected = user.Role.Contains(role)
}
);
}
ViewBag.x = new SelectList(newList, "Value", "Text");
ViewBag.Roles = new SelectList(db.Role, "Id", "RoleName", user.Role);
return View(user);
}
My View
<p>try1:</p>
#Html.ListBox("Roles", null, new { #class = "form-control", #size = 6, #style = "height: initial" })
<p>try2:</p>
#Html.ListBox("x", null, new { #size = 6, #style = "height: initial" })
Non of the 2 tries renders with pre selected values?
got it working.
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
IEnumerable<SelectListItem> roles = db.Role.Select(c => new SelectListItem{ Value = c.Id.ToString(), Text = c.RoleName, Selected = true});
var rolesSelected = new int[user.Role.Count];
var i = 0;
foreach (var role in user.Role)
{
rolesSelected[i] = role.Id;
i++;
}
ViewBag.Roles = roles.ToList();
ViewBag.RolesSelected = rolesSelected;
return View(user);
}
#Html.ListBox("RolesSelect", new MultiSelectList(ViewBag.Roles, "Value", "Text", ViewBag.RolesSelected), new { #class = "form-control", #size = 6, #style = "height: initial" })

the paging of Grid.MVC not work

Im using Grid.MVC in my MVC web application
When test it in a blank page with index controller it works successfully with pagination and filtration.
The Problem accrue when i put it in my project
the steps that i do that i make ajax request (because i don't need to reload the page) to method and return a partial view that contains the result of the search by the Grid.Mvc the result and number of pages return successfully but when i press to next page or filter it doesn't work.
Code:
View:
#using (Ajax.BeginForm("Search", "Home",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SearchResult"
})){
#Html.DropDownList("Province", "Province")
#Html.DropDownList("Cities", "Cities")
<span>price from :</span> <input type="text" name="Pricefrom" />
<span>to :</span> <input type="text" name="Priceto" />
<input type="submit" value="Search" /> }
Search Controller :
[HttpPost]
public ActionResult Search(int? page , int Province = 0, int Cities = 0, int Pricefrom = 0, int Priceto = 0)
{
var ads = db.Ad.Where(a => (Cities == 0 || a.CityId == Cities) &&
(Province == 0 || a.Cities.ProvinceId == Province)&&
(Pricefrom == 0 || a.Price >= Pricefrom)&&
(Priceto == 0 || a.Price <= Priceto)).OrderBy(a => a.AdDate).ToList();
return PartialView("_Search", ads);
}
PartialView:
#using GridMvc.Html
#model IEnumerable<Semsark.Areas.Backend.Models.Ad>
<div>
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.Id).Titled("ID");
columns.Add(c => c.AdTitle).Titled("title");
columns.Add(c => c.AdBody).Titled("body");
}).WithPaging(2).Sortable(true)
</div>
scripts and styles in the View index.cshtml :
<head>
<meta name="viewport" content="width=device-width" />
<link href="#Url.Content("~/Content/Gridmvc.css")" rel="stylesheet" />
<script src="#Url.Content("~/Scripts/gridmvc.min.js")"></script>
<script src="~/Scripts/gridmvc.lang.ru.js"></script>
<title>Index</title>
Thanks in advance for any help,
#*Webgrid using Paging in mvc 4.
View Page **.cshtml** *#
#model MvcPopup.Models.PagedEmployeeModel
#{
//ViewBag.Title = "SearchEmployee";
Layout = null;
}
#{
WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
grid.Bind(Model.Employee,
autoSortAndPage: false,
rowCount: Model.TotalRows
);
}
#grid.GetHtml(
fillEmptyRows: false,
alternatingRowStyle: "alternate-row",
headerStyle: "grid-header",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("Name",
header: "Name",
format: #<text>
#Html.ActionLink((string)item.Name, "ViewEmployeeDetail", new { id = item.id }, new { #class = "viewDialog" })</text>
),
grid.Column("Department"),
grid.Column("City"),
grid.Column("State"),
grid.Column("Country",
header: "Country"
),
grid.Column("Mobile"),
grid.Column("",
header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "EditEmployee", new { id = item.id }, new { #class = "editDialog" })
|
#Html.ActionLink("Delete", "Delete", new { id = item.id }, new { #class = "confirmDialog"})
</text>
)
})
#*-----------------------------------
Model folder under modelservices.cs file
=================================*#
public IEnumerable<Employee> GetEmployeePage(int pageNumber, int pageSize, string searchCriteria)
{
if (pageNumber < 1)
pageNumber = 1;
return db.Employees
.OrderBy(m =>m.Name)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToList();
}
public int CountAllEmployee()
{
return db.Employees.Count();
}
public class PagedEmployeeModel
{
public int TotalRows { get; set; }
public IEnumerable<Employee> Employee { get; set; }
public int PageSize { get; set; }
}
#*Controller folder under create file like employeecontroller.cs *#
using MvcPopup.Models;
using System.Globalization;
using System.Text;
namespace MvcPopup.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
ModelServices mobjModel = new ModelServices();
public ActionResult Index()
{
return View();
}
public ActionResult SearchEmployee(int page = 1, string sort = "name", string sortDir = "ASC")
{
const int pageSize = 5;
var totalRows = mobjModel.CountAllEmployee();
sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
var validColumns = new[] { "id", "name", "department", "country" };
if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
sort = "id";
var employee = mobjModel.GetEmployeePage(page, pageSize, "it." + sort + " " + sortDir);
var data = new PagedEmployeeModel()
{
TotalRows = totalRows,
PageSize = pageSize,
Employee = employee
};
return View(data);
}
------------------------
Have you tried to pass through an IQueryable list instead of an IEnumerable? According to the documentation, Gridmvc.Html requires an IQueryable for paging. There are some subtle differences between IQueryable and IEnumerable that might make a difference here.
These scripts are needed for paging:
"~/Scripts/GridMvc/URI.js"
"~/Scripts/GridMvc/gridmvc.min.js"
"~/Scripts/GridMvc/gridmvc-ext.js"

How To Populate Html.Listbox with Ajax result using mvc 4

In My MVC 4 App i want to populate Html.LisboxFor with an Ajax result.
My View:
#using (Html.BeginForm("UpdatePriority", "Priority", FormMethod.Post))
{
#Html.Hidden("myListBoxValuesValues")
<div class="row">
<div class="col-md-2">
<label>FA:</label>
#Html.ListBoxFor(m => m.FA, new MultiSelectList(#Model.FA), new { #class = "lbx_FA" })
</div>
<div class="col-md-1">
<input id="btnAdd" type="button" value=" > " onclick="addItem();" />
</div>
<div class="col-md-2">
<label>CEID list:</label>
#Html.ListBoxFor(model => model.CEIDs, new MultiSelectList(Model.CEIDs), new { #class = "lbx_CEIDs" })
</div>
...and so on..
My my controller function (returns string of a json model):
public string getCeidPerFA(string FA)
{
return unitOfWork.ToolRequiredRepository.getCEIDsPerFA_Scenario(DAL.UnitOfWork.Scenario, FA);
}
The repository function:
internal string getCEIDsPerFA_Scenario(string scenario, string FA)
{
//create the result list (FAs):
List<string> FAs = FA.Split(',').ToList();
var CEIDs = from row in context.ToolRequireds
where row.Scenario == scenario && FAs.Contains(row.FA)
select row.CEID;
List<string> lst = CEIDs.Distinct().ToList();
//create Json Result:
List<SelectListItem> items = new List<SelectListItem>();
foreach (var ceid in lst)
{
items.Add(new SelectListItem { Text = ceid, Value = ceid });
}
return Json.Encode(items);
}
My Script:
function addItem() {
var result = "";
var x = document.getElementById("FA");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected == true) {
result += x.options[i].value + ",";
}
}
result = result.substring(0, result.length - 1);
$.ajax({
url: "#(Url.Action("getCeidPerFA", "CeidSelection"))",
data: { "FA": result },
success: function (data) {
if (data.length > 0) {
JSON.pa
$("#CEIDs").append(JSON.parse(data));
}
else
alert("No Result");
},
error: function (xhr) {
alert("Something went wrong, please try again");
}
});
}
My code is wrong but i have no idea how to do so.
Any help will be very appreciated.
loop through the data result like this
$('#CEIDs').empty();
$.each($(data), function(key, value) {
$('#CEIDs').append('<option value=' + key + '>' + value + '</option>');
});

ASP.NET MVC AjaxActionLink

My partialview didnot load, i'm using AjaxActionLink
here is my view where i call my partialview
#foreach (var p in Model.Rooms)
{
<div class="room">
<h3>#p.RoomTitle</h3>
<img src="#p.PhotoRoom" alt="room"/>
<h4>#p.TitlePrice</h4>
<blockquote>#p.Description</blockquote>
#Ajax.ActionLink("Order room", "PartialDetail", new { #p.RoomID }, new AjaxOptions { UpdateTargetId = "results", LoadingElementId = "loading",HttpMethod = "POST",InsertionMode = InsertionMode.InsertAfter})
</div>
}
Here is my controller
public PartialViewResult PartialDetail(int roomid)
{
Room rooms =
repository.Room.FirstOrDefault(p => p.RoomID == roomid);
var viewModel = new RoomEditViewModel
{
RoomID = rooms.RoomID,
RoomTitle = rooms.RoomTitle,
Description = rooms.Description,
PhotoRoom = rooms.PhotoRoom
};
ViewBag.room = roomid;
return PartialView(viewModel);
}
fixed your ajax action link
What you set
#Ajax.ActionLink("Order room", "PartialDetail", new { #p.RoomID }
Should be
#Ajax.ActionLink("Order room", "PartialDetail", new { roomid = #p.RoomID }
As a recommendation set the aceepted protocols in your action
[HttpPost]
public PartialViewResult PartialDetail(int roomid)

MVC3 - Asynchronous Pagination

I have a list of objects which uses paging in my home > index.cshtml. When a user clicks through each page of objects I only want to refresh that portion of the page and nothing else. How would I accomplish this?
Ideally I want to use Async Methods and ControllerActions...
Controllers > HomeController.cs
public ViewResult Index(int page = 1) {
ProductsListViewModel viewModel = new ProductsListViewModel {
Products = repository.Products
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo {
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
}
};
return View(viewModel);
}
Home > Index.cshtml:
#model SportsStore.WebUI.Models.ProductsListViewModel
#{
ViewBag.Title = "Products";
}
#foreach (var p in Model.Products) {
<div class="item">
<h3>#p.Name</h3>
#p.Description
<h4>#p.Price.ToString("c")</h4>
</div>
}
<div class="pager">
#Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
</div>
HtmlHelper > PagingHelper.cs
namespace SportsStore.WebUI.HtmlHelpers {
public static class PagingHelpers {
public static MvcHtmlString PageLinks(this HtmlHelper html,
PagingInfo pagingInfo,
Func<int, string> pageUrl) {
StringBuilder result = new StringBuilder();
for (int i = 1; i <= pagingInfo.TotalPages; i++) {
TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
result.Append(tag.ToString());
}
return MvcHtmlString.Create(result.ToString());
}
}
}
You could use AJAX. The first step is to put the contents that you want to be refreshed into a partial and into its own div:
#model SportsStore.WebUI.Models.ProductsListViewModel
#{
ViewBag.Title = "Products";
}
<div id="products">
#Html.Partial("_products", Model.Products)
</div>
<div class="pager">
#Html.PageLinks(Model.PagingInfo, x => Url.Action("Index", new { page = x }))
</div>
and then of course you will have the corresponding _Products.cshtml partial:
#model IEnumerable<SportsStore.WebUI.Models.ProductViewModel>
#foreach (var p in Model.Products) {
<div class="item">
<h3>#p.Name</h3>
#p.Description
<h4>#p.Price.ToString("c")</h4>
</div>
}
and then adapt your controller action so that it is capable of responding to AJAX requests:
public ActionResult Index(int page = 1)
{
var viewModel = new ProductsListViewModel
{
Products = repository.Products
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
}
};
if (Request.IsAjaxRequest())
{
return PartialView("_Products", viewModel);
}
return View(viewModel);
}
and now all that's left is to AJAXify your pagination anchors. Could be done in a separate javascript file where you could use jQuery to subscribe to the .click() event of them and replace the default action with an AJAX request:
$(function() {
$('.pager a').click(function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(products) {
$('#products').html(products);
}
});
// prevent the default redirect
return false;
});
});

Resources