I'm trying to load partial page contents with jquery.load() method it is loading content but not loading styles. I have searched internet but couldn't found any solution. I'm sharing what i have done so far.
JQUERY:
$(function () {
var site = site || {};
site.baseUrl = site.baseUrl || "";
$(document).ready(function (e) {
$(".partialContents").each(function (index, item) {
var url = site.baseUrl + $(item).data("url");
if (url && url.length > 0) {
$(item).load(url, function (response, status, xhr) {
if (status == "error") {
alert(xhr.status);
}
return false;
});
}
});
});
});
View:
<div class="owl-carousel owl-carousel5">
<span class="partialContents" data-url="#Url.Action("LoadNew","Home")"></span>
</div>
Controller Action:
public async Task<ActionResult> LoadNew()
{
var viewModel = new CategoryViewModel();
viewModel.Products = await db.Products.Include(c => c.Reviews).Include(c => c.CategoryContents).Include(c => c.Affiliates).ToListAsync();
return PartialView("_NewProducts", viewModel);
}
As you have mentioned in comments that you have referenced css in Layout, you have to return View instead of PartialView.
So,
public async Task<ActionResult> LoadNew()
{
var viewModel = new CategoryViewModel();
viewModel.Products = await db.Products.Include(c => c.Reviews).Include(c => c.CategoryContents).Include(c => c.Affiliates).ToListAsync();
return View("_NewProducts", viewModel);
}
should do the work.
Related
So im using jquery.dataTables.js to display about a thousand rows, while only showing about twenty at a time. The problem is with the dropdownlist on every line it takes about 10 seconds to load the page and shows a lot more of the records while loading. I thought about doing it after page load with ajax but not sure how to do that cleanly with all of them. Any ideas.
#for (int i = 0; i < Model.billVersion.Count; i++)
{<tr>
<td>#Html.DisplayFor(model => model.billVersion[i].billNumber)#Html.HiddenFor(model => model.billVersion[i].billNumber)</td>
<td>#Html.DisplayFor(model => model.billVersion[i].lrNumber)</td>
<td>#Html.DisplayFor(model => model.billVersion[i].previousYear)</td>
<td>#Html.DisplayFor(model => model.billVersion[i].committeeRec)</td>
<td>#Html.DropDownListFor(model => model.billVersion[i].committeeID, #Model.committeDropDown, "")</td>
<td>#Html.CheckBoxFor(model => model.billVersion[i].save_Remove)</td>
</tr>
}
An application of Jquery UI autocomplete:
!function ($) {
var cache = {};
$("[data-options]").each(constructAjaxOptions);
function constructAjaxOptions() {
var el = $(this),
acEl = $(el.clone(false)),
url = el.attr('data-options'),
initialLabel = el.attr('data-initial-label') || el.val(),
myCache = cache[url];
if (!myCache) {
myCache = cache[url] = {};
}
el.hide();
acEl
.removeAttr('id').removeAttr('name')
.val(initialLabel)
.insertAfter(el)
.autocomplete({
autoFocus: true,
minLength: 0,
source: function (request, response) {
var term = request.term;
if (term in myCache) {
response(myCache[term]);
return;
}
$.getJSON(url, request, function (data, status, xhr) {
myCache[term] = data;
response(data);
});
},
focus: function (event, ui) {
// Overridden to keep the value of the field
// from flashing in the textbox.
return false;
},
select: function (event, ui) {
acEl.val(ui.item.label);
el.val(ui.item.value);
return false;
}
});
}
}(jQuery);
.cshtml
<input type="text" id="#Html.IdFor(model => model.billVersion[i].committeeID)" name="#Html.NameFor(model => model.billVersion[i].committeeID)" value="#Value"
data-options="#Url.Action("BillVersions", "Options")" data-initial-label="#model => model.billVersion[i].commiteeName" />
Within an MVC action:
var model = billVersions.Select(o => new
{
value = o.committeeID,
label = o.commiteeName
})
.ToList();
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = model };
I am very new to MVC, and am try to set up a series of cascading drop down lists using this example.
But I am stuck a little bit, because I don't know how to get the value from the second drop down and send it to controller when I press the appropriate button.
Here is my view:
<script type="text/javascript">
$('#list').change(function() {
var selectedClient = $(this).val();
if (selectedClient != null && selectedClient != '') {
$.getJSON('#Url.Action("SelectC")', { clientID: selectedClient }, function (client) {
var campaingSelect = $('#clist');
campaingSelect.empty();
$.each(client, function(index, clients) {
campaingSelect.append($('<option/>', {
value: clients.value,
text: clients.text
}));
});
});
}
});
</script>
#using (Html.BeginForm("CreateNewCampaign", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.LabelFor(m => m.alreadyCreatedCampaignName, "Name:")
#Html.DropDownList("clist","-- Select Client -2-")
<input type="Submit" name="button" value="Select" class="btn btn-primary" />
}
Controller:
public ActionResult SelectC(int clientId, CampaignModel model, FormCollection form)
{
Session["ClientID"] = clientId;
ViewBag.ClientName = "You're using: " + Session["ClientName"];
var CampaignInf = CampaignManagementService.GetCampaigns((string) Session["ticket"], clientId);
List<AlreadyCreatedCampaignList> itemas = new List<AlreadyCreatedCampaignList>();
foreach (var element in CampaignInf)
{
itemas.Add(new AlreadyCreatedCampaignList() {CampId = element.Key, CampName = element.Value});
}
var listOfCam = new SelectList(itemas, "campID", "campName", 1);
return Json(listOfCam.Select(x => new {value = x.Value, text = x.Text}), JsonRequestBehavior.AllowGet);
}
I want to get the value to other controller, and I am not sure of the right way to go about doing this.
You can get value of dropdownlist just by giving it ID and call $("#id").val();, then you can transfer it to the controller through ajax maybe.
Here is mine, try it
public ActionResult ActionName(string dropdown_value){
//your code
}
<script>
$(document).ready(function(){
$("submit").click(function(){
$.ajax({
url:"Controller/ActionName",
datatype: "POST",
data: { dropdown_value : $("#clist").val() },
success : function(){ //your code if success }
});
});
});
</script>
I have a controller that I get result exampleController.cs:
public expChart{
...
public ActionResult ByContainer(int id)
{
var elementIds = _systemSettings.Z3FromZBIds; // CritialWorkPermitIds;
var kpiElements = CacheService.AllVisibleElements
.Where(x => elementIds.Contains(x.Id)).ToList();
var container = _kpiContainerService.Find(id);
var result = _kpiTrendService.MonthByContainer(kpiElements, container);
return AsJson(result);
}
}
I call it in example.cshtml:
<div class="panel" style="display: none;" id="bottom-area-trend-charts" ng-ontroller="exampleController">
<div >
TEST
{{element.Name}}
</div>
</div>
I think it is something wrong with my calling. How can I call the result in my controller?
Thanks in advance
Use something like this:
<script type="text/javascript">
$(function () {
$.ajax({
url: "/YourController/ByContainer",
type: "GET",
dataType: 'html',
data: { id: 10 }, // the value id for call your controller
success: function (data) {
// make sure your result variable is enumerable.
$(data).each(function (index, element) {
$("#bottom-area-trend-charts div").append("<p>" + element.Name + "</p>");
});
},
error: function (xqr, errorMessage) {
alert(errorMessage);
}
});
});
</script>
And change your action to this:
public JsonResult ByContainer(int id)
{
var elementIds = _systemSettings.Z3FromZBIds; // CritialWorkPermitIds;
var kpiElements = CacheService.AllVisibleElements
.Where(x => elementIds.Contains(x.Id)).ToList();
var container = _kpiContainerService.Find(id);
var result = _kpiTrendService.MonthByContainer(kpiElements, container);
return Json(result, JsonRequestBehavior.AllowGet);
}
My View Code:
Script and Css:
<link href="#Url.Content("~/Content/jquery-ui-1.8.18.custom.css")" rel="stylesheet"type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.18.custom.min.js")" type="text/javascript"></script>
Input text:
#Html.TextBoxFor(model => model.Filter.HouseName, new { style = "width: 205px", onKeyUp = "updateHouseNames()" })
Javascript:
function updateHouseNames() {
var houseArray = new Array();
$.post('#Url.Action("LoadHouses")', { houseName: $("#Filter_HouseName").val() }, function(houses) {
houseArray = houses;
});
$("#Filter_HouseName").autocomplete({
source: houseArray
});
}
Controller method:
[HttpPost]
public JsonResult LoadHouses(string houseName)
{
var houses = this.HouseService.SelectByName(houseName).Select(e => new String(e.Name.ToCharArray())).ToArray();
return Json(houses);
}
I debug the javascript and the houses are selected.. but the results are not displayed in autocomplete. Why?
I don't really think you should be doing it this way. If you need to customize the logic then use a callback on the autocomplete method:
$(function () {
$('#Filter_HouseName').autocomplete({
minLength: 1,
source: function (request, response) {
var term = request.term;
var houseArray = new Array();
$.post('#Url.Action("LoadHouses")', { houseName: term }, function(houses) {
houseArray = houses;
response(houseArray);
});
}
});
});
I wanna make twitter like microblog site which other users can follow my posts.
For that i made page with all currently registered users. In front of each name there is button to follow/unfollow user. (Like in Twitter)
View -
#{
ViewBag.Title = "Users";
}
#model MembershipUserCollection
#foreach (MembershipUser item in Model)
{
if(User.Identity.Name != item.UserName)
{
<li>#item.UserName
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="follow-user fg-button ui-state-default"/></span>
</li>
}
}
<script type="text/javascript">
$(".follow-user").live("click", function (e) {
e.preventDefault();
var data = $(this).attr("id");
var spid = '#sp-' + data;
var btnid = '#' + data;
var val = $(this).attr('value');
$.ajax({
type: "POST",
url: "User/FollowUser",
data: { id: data },
cache: false,
dataType: "json",
success: function () {
if (val == 'Follow') {
$(btnid).attr('value', 'Unfollow');
}
else {
$(btnid).attr('value', 'Follow');
}
}
});
});
</script>
Controller -
public ActionResult Index()
{
return View(Membership.GetAllUsers());
}
public void FollowUser(string id)
{
ViewData["test"] = "test";
var n = FollowingUser.CreateFollowingUser(0);
n.FollowingId = id;
n.FollowerId = User.Identity.Name;
string message = string.Empty;
var list = new List<FollowingUser>();
list = (from a in db.FollowingUsers where a.FollowerId == User.Identity.Name && a.FollowingId == id select a).ToList();
if (list.Count() == 0)
{
try
{
db.AddToFollowingUsers(n);
db.SaveChanges();
}
catch (Exception ex)
{
message = ex.Message;
}
}
else
{
db.DeleteObject((from a in db.FollowingUsers where a.FollowerId == User.Identity.Name select a).FirstOrDefault());
db.SaveChanges();
}
}
FollowingUsers Table -
Now i wanna change button status on page load checking database whether he is already followed or not.
Ex- If user already followed it should display like below.
When you show this view to a user where this button is displayed, Load the status also, if the person is following or not.
public ActionResult Index()
{
var model = new MemberShipViewModel();
//We check here if the logged in user is already following the user being viewd
foreach(var member in Membership.GetAllUsers())
{
var user = (from a in db.FollowingUsers where a.FollowerId == User.Identity.Name && a.FollowingId == member.UserName select a).FirstOrDefault();
model.Members.Add(new Member{UserName = member.UserName,IsFollowing=user!=null});
}
//This line will remove the logged in user.
model.Members.Remove(model.Members.First(m=>m.UserName==User.Identity.Name));
return view(model);
}
In your index view model, you need to make some changes.
#model MemberShipViewModel
#foreach (var item in Model)
{
<li>#item.UserName
if(!item.IsFollowing)
{
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="follow-user fg-button ui-state-default"/></span>
}
else
{
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="unfollow-user fg-button ui-state-default"/></span>
}
</li>
}
$(".follow-user").live("click", function (e) {
e.preventDefault();
var data = $(this).attr("id");
var spid = '#sp-' + data;
var btnid = '#' + data;
var val = $(this).attr('value');
$.ajax({
type: "POST",
url: "User/FollowUser",
data: { id: data },
cache: false,
dataType: "json",
success: function () {
if (val == 'Follow') {
$(btnid).attr('value', 'Unfollow');
}
else {
$(btnid).attr('value', 'Follow');
}
}
});
});
You need to write some javascript now. Nobody is going to write full software for you.
Seems you are missing very basic programming skills.
cheers