MVC: Can't make fancybox work - model-view-controller

I am trying to update an existing application and wants to display modal using fancybox. On other functionalities, I was able to display the fancybox but for some reason cannot do it on a particular view.
Here is my main view declaration:
#Html.ActionLink(Strings.Link_ViewFullList, "OrganisationFullList", new { id = 1 }, new { #class = "fancybox fancybox.ajax" })
Then here is my "organisationFullList" cshtml file.
#model ProjectOrganisationModel
#{
ViewBag.Title = Strings.PageTitles_Organisations;
}
<div class="row">
<div class="col-lg-10">
#if (Model.Organisation != null && Model.Organisation.Any())
{
<ul class="list-unstyled">
#foreach (var organisation in Model.Organisation)
{
<li>
#Html.RadioButton("organisationList", organisation.Name)
#Html.Label(organisation.Name, new { style = "font-weight: normal" })
</li>
}
</ul>
}
</div>
</div>
Here is my controller code:
public ActionResult OrganisationFullList(int id)
{
var organisationList = new ProjectOrganisationModel();
organisationList.Organisation = GetOrganisations();
return View(organisationList);
}
When I click on the link, it displays a new screen instead of the modal. It redirects to this URl:
https://localhost:44300/project/1/organisationfulllist

#Html.ActionLink causes you to redirect to another page.
Rather than using #Html.ActionLink use #Ajax.ActionLink
#Ajax.ActionLink(
"View Full List Ajax",
"OrganisationFullList", //Action
"YourController", //Controller
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "showFancyBox" //call back
}
)
Call back function:
function showFancyBox(data) {
$.fancybox.open({ "content": data });
}
Dont forget to include jquery.unobtrusive-ajax.min.js you need it to use #Ajax helpers
<script type="text/javascript" src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>

Related

MVC Partial View Returns Whole Page Instead of Just the Partial

I have the following partial view named "_transactions":
<div id="section-transactions" class="documentsanchor">
</div>
<div>
<div class="row">
<div class="col-lg-12">
<div>
<h4 class="company-headings">#ViewBag.SecSymbol Transactions</h4>
</div>
<div>
</div>
</div>
I render it using
#{Html.RenderAction("Transactions", "Company");}
and this is the Transactions method from the Company controller:
public async Task<PartialViewResult> Transactions()
{
ViewBag.SecSymbol = "test";
return PartialView("_transactions");
}
It's on a page with other partial views.
This works fine. However, I have a button on the page that should get a new partial view and replace the current one. It makes an ajax call as follows
$("#btn_transactions").click(function (e) {
var url = "Company/Transactions";
$.ajax({
url: url,
success: function (result) {
alert(result);
$('#transTarget').html(result);
},
error: function () {
alert("Error occured");
}
});
})
The issue is that the whole page is returned in "result", that is, all partials as well as the layout, when all I want is the transactions partial. What am I doing wrong?
Add this code in partial view
#{
Layout=null;
}
Make sure you have the route set up in your configs -
routes.MapRoute("CompanyTransactions", "company/transactions", new { controller = "Company", action = "Transactions" });

how to call Partialview inside another view in asp.net mvc

If i click Execute button i m redirecting my action to viewpage(GetSection), in this page the partialview(CoverPage) should render automaticly without any event, all it has navbar and CoverPage is also part of navbar, all navbar values are coming from database, i tried "#Html.RenderPartial("CoverPage")" syntax, but it doesn't work for me,and here is my View page
<table style="width:auto">
#foreach (Test_Section p in Model)
{
<tr>
<td>
<div id="ajaxnav" class="navbar-left">
<ul class="nav nav-pills nav-stacked">
<li class="navigationLink">
#Ajax.ActionLink(p.SectionName, p.Title, new { id = p.StdSectionId },
new AjaxOptions
{
UpdateTargetId = "getHtml",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
}, new { style = "color:black" , #class = "navigationLink" })
</li>
</ul>
</div>
</td>
</tr>
}
<div id="getHtml" class="divhtml"></div>
</table>
and the controller is
public ActionResult GetSections()
{
Test_Section[] section = context.Test_Section.ToArray();
return PartialView(section);
}
so please help me.
From your comments, it looks like you want to load the response of the click event of the first link on the page load.
You can trigger the link click on the document ready event with jquery trigger method.
$(function () {
if ($("a.navigationLink").length) {
$("a.navigationLink").eq(0).trigger( "click" );
}
});

Saving multiple partial views from one main page

Here is my requirement :
I am designing a page to add a vehicle to the database :
Normal vehicle information [Model - Inventory]
Some other features [Model - IList]
Here is my index.cshtml page
#model Model.ViewModel.VehicleViewModel
<div>
<div class='col-md-12'>
<div class="form-group">
<input id="mainFormSubmit" type="button" value="Save" class="btn btn-default" />
</div>
</div>
#{Html.RenderPartial("~/Views/Shared/_InventoryPartial.cshtml", Model.InventoryVM);}
#{Html.RenderPartial("~/Views/Shared/_StandardFeaturePartial.cshtml", Model.StandardFeatures);}
</div>
<script type="text/javascript">
$('#mainFormSubmit').click(function () {
$('#InventoryForm').submit();
$("#StandardFeatureForm").submit();
});
</script>
This is my view model class
public class VehicleViewModel
{
public InventoryViewModel InventoryVM { get; set; }
public IList<StandardFeature> StandardFeatures { get; set; }
}
The Inventory partial view [_InventoryPartial.cshtml]
#model Model.ViewModel.InventoryViewModel
#{
var options = new AjaxOptions() { HttpMethod = "Post" };
}
<div class="container">
<div class="row">
<div class="col-md-12">
#using (Ajax.BeginForm("InventorySave", "AddVehicle", options, new { id = "InventoryForm" }))
{
<fieldset>
<legend>Inventory Info</legend>
<div class='col-md-6'>
<!-- VIN input-->
<div class="form-group">
#Html.LabelFor(x => x.VIN, new { #class = "col-md-4 control-label" })
<div class="col-md-7">
#Html.TextBoxFor(x => x.VIN, new { #class = "form-control", #placeholder = "VIN" })
</div>
</div>
</div>
</fieldset>
}
The standard feature partial view [_StandardFeaturePartial.cshtml]
==
#model IEnumerable<Model.DomainModel.StandardFeature>
#{
var options = new AjaxOptions() { HttpMethod = "Post" };
}
<div class="container">
<div class="row">
<div class="col-md-12">
#using (Ajax.BeginForm("StandardFeatureSave", "AddVehicle", options, new { id = "StandardFeatureForm" }))
{
When I am clicking on index page SAVE button, only
$('#InventoryForm').submit();
$("#StandardFeatureForm").submit();
last one(StandardFeatureForm) is executing.
Please let me know if this process is correct, and what could be the reason of this issue.
You should not call the submit method twice. Depending of the browser you can face different issues :
the form submission causes the browser to navigate to the form action and the submission
of the first may prevent the submission of the second
The browser could detected there are two requests and discards the
first submit.
In your case it will be easier to wrap your two partial views inside a unique form.
#using (Ajax.BeginForm("InventorySave", "AddVehicle", FormMethod.Post, new { id = "InventoryForm" }))
{
#{Html.RenderPartial("~/Views/Shared/_InventoryPartial.cshtml", Model.InventoryVM);}
#{Html.RenderPartial("~/Views/Shared/_StandardFeaturePartial.cshtml", Model.StandardFeatures);}
}
However when the partial views render they are not generating the correct name attributes for the larger modelModel.ViewModel.VehicleViewModel you want to use :
public void InventorySave(VehicleViewModel vehicleViewModel) {}
In this case you should use EditorTempmlate instead of partial views. It's simple to do from your partial views and this post should help you :Post a form with multiple partial views
Basically, drag your partials to the folder ~/Shared/EditorTemplates/
and rename them to match the model name they are the editor templates
for.
Finally something like :
#model Model.ViewModel.VehicleViewModel
#using (Html.BeginForm("InventorySave", "AddVehicle", FormMethod.Post, new { id = "InventoryForm" }))
{
#Html.EditorFor(m => m.InventoryVM);
#Html.EditorFor(m => m.StandardFeatures});
}
The Ajax.BeginForm helper already has a submit event associated to it which creates an Ajax POST request. When you are manually submitting your form using $('#InventoryForm').submit();, you're calling both and the submit events which can have strange side effects.
There are a few ways around this. Here is one solution
Change your forms to a regular HTML form using the Html.BeingForm helper.
Amend your script to create ajax requests and use the form data
$('#InventoryForm').submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(r) {
//Do something
});
});
$('#StandardFeatureForm').submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(r) {
//Do something
});
});
Hope this helps

Client side paging for Asp.Net MVC3

this is my MVC action that returns a list of posts:
public ActionResult Posts()
{
var blogPost = _blogRepository.GetAllPost();
var blogPostViewModel = blogPost.ConvertToPostViewModelList();
return View("Posts", blogPostViewModel);
}
and also this is my View
#model IEnumerable<Blog.Web.UI.ViewModels.PostViewModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
#foreach (var item in Model)
{
<div>
<h3>
#Html.ActionLink(item.Title, "Post", "Blog", new { postId = item.Id, postSlug = item.UrlSlug }, null)
</h3>
</div>
<div>
<span>Category: </span>#item.Category.Name
</div>
<div>
<span>Tag: </span>#item.Tag.Name
</div>
<div>
#item.CreationDate.ToLongDateString()
</div>
<div>
#Html.DisplayTextFor(p => item.Body)
</div>
}
</div>
I want to implement a Client Side paging for this page that render all of the post by date , is it possible ?? or I should change my code to make it server side ??
http://haacked.com/archive/2009/04/13/using-jquery-grid-with-asp.net-mvc.aspx
It's old but relevant and should help you achieve what your looking for.

MVC3 Ajax ChildAction

I am having a difficult time figuring out how to get AJAX working with child actions in MVC3. I have a View that contains a section rendered by a child action. That child action renders a partial view which has a paged list on it. I need to make it so that when a user clicks on another page number on the page list pager only the bottem part of the view containing a list of videos will be updated. I have included my code and would really appreciate some help as I am still confused on some of the ways MVC3 works with AJAX. Thanks in advance.
My View:
#model UltimateGameDB.Domain.Entities.Video
#{
ViewBag.Title = "Video Home";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using PagedList
#using PagedList.Mvc
#section MainBanner {
<section id="videos-featured">
#Html.Partial("_Video", Model)
<div id="videos-featured-detail">
#Html.Partial("_VideoDetail", Model)
#Html.Action("MiniFeaturedVideo", "Video")
</div>
</section>
}
#Html.Action("RecentVideos", "Video", new { page = ViewBag.page })
My Controller Methods:
public ActionResult VideoHome(Guid? selectedVideoId, int? page)
{
var pageIndex = page ?? 1;
ViewBag.page = pageIndex;
if (selectedVideoId == null)
{
selectedVideoId = ugdb.Videos.Where(v => v.IsFeatured == true).OrderBy(v => v.Timestamp).FirstOrDefault().VideoID;
ViewBag.Autoplay = 0;
}
else
{
ViewBag.Autoplay = 1;
}
return View(ugdb.Videos.Find(selectedVideoId));
}
[ChildActionOnly]
public ActionResult RecentVideos(int? page)
{
IQueryable<Video> videoList = ugdb.Videos.OrderBy(v => v.Timestamp);
var pageIndex = page ?? 1;
var onePageOfVideos = videoList.ToPagedList(pageIndex, 8);
ViewBag.OnePageOfVideos = onePageOfVideos;
return PartialView("_RecentVideos");
}
My Partial View:
#using PagedList
#using PagedList.Mvc
<div id="main-content" class="videos">
<section>
<a class="body-title"><span>RECENT VIDEOS</span><span class="title-arrow"></span></a>
<div class="main-hr"></div>
#foreach (var video in ViewBag.OnePageOfVideos)
{
<a class="video-entry" href="#Url.Action("VideoHome", "Video", new { selectedVideoId = video.VideoID })">
<img src="http://img.youtube.com/vi/#video.YouTubeID/default.jpg" alt="#video.VideoName" />
<div class="video-details">
<h2>#video.VideoName</h2>
<p>#video.VideoType</p>
</div>
</a>
}
</section>
<div class="pagination">
#Html.PagedListPager((IPagedList)ViewBag.OnePageOfVideos, page => Url.Action("VideoHome", "Video", new { page = page }), PagedListRenderOptions.OnlyShowFivePagesAtATime)
</div>
</div>
What you're probably gonna want to do is insert an AjaxForm after the main-content div and end it before the main-content div closes.
Then the PagedListPager can submit to a Json Method in your controller which will return the content (e.g. list of videos) for the Ajax form to update.

Resources