I am using ordered list design to to make my twitter app to view the tweets. Every Time I call the ajax insert, it puts puts another copy of the ajax link on the page . I am just trying to get the next set of tweets from the controller and inserting them so it lines up. I have tried moving the tags around and but the additional ajax buttons keep showing up.
Thinking it was a css problem i stripped it all out. Wasnt the issue. I will have to reformat my list again to put the closing and openning tags before and after the code block.
I just tried to putting it in a partial view and I put the ajax code in the layout.
Ajax Action Link
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
Partial View
<div id="TweetBox">
<div class="TwitterMessageBox">
<ol>
<li class="TweetLineBody">
#foreach (var item in Model)
{
#Html.Hidden(item.StatusId, item.StatusId)
<div class="TwitProfileImage">
<img src=#Url.Content(item.ImageUrl) alt="#item.ScreenName" />
</div>
<div class="TwitRealName">
#item.User
</div>
<div class="TwitNickName">
#MvcHtmlString.Create(#Html.Namify(#item.ScreenName))
</div>
<div class="TweetText">
#MvcHtmlString.Create(#item.Tweet)</div>
<div class="TweetTime">
#Html.RelativeDate(#item.Created)</div>
<div class="TweetRating">
Rating</div>
}
</li>
</ol>
</div>
</div>
The Controller is just a basic Enumerable List on the Home/ Index
This is the behavior
Lets say you have an ajax call that gets data from a controller action. It inserts before on a targetid thats a div id.
The initial view is perfect
AJAX UPDATE HTML LINK // You click it to get the controller invoke the ajax and get the data
Tweet 1
Tweet 2
etc = its perfect and aligned
You click the Ajax action link in your webpage, It goes out and gets the data but adds a second like like this
AJAX UPDATE HTML LINK
AJAX UPDATE HTML LINK
Tweet 1
Tweet 2 // alignment is still perfect but you have the 2nd ajax links
Now click the ajax link a 3rd time
// alignment is still perfect but you have the 2nd ajax link at top and one sandwiched
AJAX UPDATE HTML LINK
AJAX UPDATE HTML LINK
Tweet 1
Tweet 2
// alignment is still perfect but you have the 2nd ajax link at top and one sandwiched
Plus the Tweets results
AJAX UPDATE HTML LINK
Tweet 1
Tweet 2 // alignment is still perfect but you have the 2nd ajax links at the top and a 3rd List is inserted betweet 2/3
Controller Code per request:
public class HomeController : Controller
{
//
// GET: /Home/
private TwitterContext twitterCtx;
public ActionResult Index()
{
twitterCtx = new TwitterContext();
List<TweetViewModel> friendTweets = (from tweet in twitterCtx.Status
where tweet.Type == StatusType.Public
select new TweetViewModel
{
ImageUrl = tweet.User.ProfileImageUrl,
UserId = tweet.UserID,
User = tweet.User.Name,
ScreenName = tweet.User.Identifier.ScreenName,
StatusId = tweet.StatusID,
Tweet = HomeController.AddWebAndTwitterLinks(tweet.Text),
Created = tweet.CreatedAt
})
.ToList();
return View(friendTweets);
}
My Desired Behavior is 1 ajax link to call the controller and the data inserts
Without seeing all the code, I can only assume you don't have your views sorted out. Your controller appears to be returning the full Index view. If you put your tweet box into a partial view, your ajax action needs to be returning that partial view.
Related
Trying to render all the Contacts using ajax (This is a snippet)
So on click, it will list the contacts in a div on the update action. I have tested with a basic date function (see commented out render action Controller) to make sure ajax part could work and that does, but handling the list I have hit a wall with and going round in circles
GSP:
<g:remoteLink controller="event" action="showContacts" update="divContactList">Show Contacts!</g:remoteLink>
<div id="divContactList">Show contacts Here...
<g:each in="${contactList}" status = "i" var="contact">
<p>${contact.forname}</p>
<p>${contact.email}</p>
</g:each>
</div>
Controller:
def showContacts = {
def contactList = Contact.findAllByUser(lookupPerson())
// render "The time is now ${new Date()}"
render([contactList: contactList])
}
So overall it's not showing anything from the contactList in the web page, help on this would be appreciated
_templateName.gsp:
<g:each in="${contactList}" status = "i" var="contact">
<p>${contact.forname}</p>
<p>${contact.email}</p>
</g:each>
GSP:
<g:remoteLink controller="event" action="showContacts" update="divContactList">Show Contacts!</g:remoteLink>
<div id="divContactList">Show contacts Here...
<g:render template="layouts/templateName" model="[contactList: contactList]" />
</div>
Controller:
def showContacts = {
def contactList = Contact.findAllByUser(lookupPerson())
// render "The time is now ${new Date()}"
render(template: 'layouts/templateName', model:[contactList: contactList])
}
Clicking the remote link will send an AJAX call to the showContacts action, get an HTML answer and update the content of divContactList with the returned answer.
The showContacts action will render a template with the same name, passing it the contactList as part of the model.
If you would like the AJAX call to render the list of contacts you can try one of the following options:
Content Centric Ajax - Have the showContacts action render a template which displays the list of contacts
Data Centric Ajax - Have the showContacts action send a JSON/XML response representing the list of contacts and have a client side JavaScript code render this JSON/XML as the contact list
I have a main view and the URL for this view has a Action/Controller/Area and id value, something like:
http://localhost:56513/Incident/IncidentHome/Index/8c02a647-a883-4d69-91be-7ac5f7b28ab7
I have a partialview in this main view, one that calls methods in the controller via Ajax. This partial view needs to know the ID value of the url for the parent page. I found how to do this is through 'ParentActionViewContent'. Something like:
using (Ajax.BeginForm("UpdatePersonalStatusPanel", "Status", new { area = "Tools" , id = ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() }, new AjaxOptions { UpdateTargetId = "divPersStatus" }))
{
<p style="text-align: center;">
<span class="editor-label">#Html.LabelFor(m => m.StatusText)</span> <span class="editor-field">#Html.EditorFor(m => m.StatusText)</span>
<input type="submit" value="Change Current Status" />
</p>
}
Now, this works fantastic for calling the controller method. The ID is passed correctly so that the controller can then see it in the routedata. I use the id to perform a database call, and then return the partialview again. The problem is on the return. I get a 'Object reference not set to an instance of an object' on the ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() bit in the ajax.beginform , and my targetid doesn't refresh.
Clearly I must be doing something wrong. Does someone else have a better way to see the parent view's routedata through Ajax?
If I'm understanding you correctly, this partial view calls itself. So ParentActionViewContext works the first time because the first time your main view calls an action using this partial view. However, later an ajax call directly returns this partial view. When the partial view is invoked directly there is no Parent View action hence the null reference on ParentActionViewContext.
Rather than deal with with route data I recommend including the id in the model of your partial view.
new { area = "Tools" , id = Model.Id }
I'm new to MVC (MVC3) so not sure about the best way to implement this.
I want to create a single "main" view (not strongly-typed). This "main" view will contain multiple strongly-typed partial views that each contain a form. Each partial view will therefore post back to their own POST action that does whatever. The problem I see is that when a partial view posts back, it needs to only update the partial view itself and not affect the other partial views on the page.
When I postback from a partial view now, it just returns the partial view alone back, rather than the entire "main" page.
How can this functionality be achieved in MVC3? (from a high-level perspective)
Thanks
You can post data by AJAX.
In my example I use jQuery:
<div id="first-form" class="form-container">
#Html.Partial("FirstPartial")
</div>
<div id="second-form" class="form-container">
#Html.Partial("SecondPartial")
</div>
// and here go rest forms
Your partial view may be following:
#model YourModelClass
#using (Html.BeginForm())
{
// some fields go there
}
<input type="button" value="Save Form Data" class="save-button"/>
Js would be following:
$("input.save-button").on("click", function () {
var button = $(this);
var container = button.closest("div.form-container");
var url = container.find("form").attr("action");
container.busy($.post(url, function (response) {
container.html(response);
}));
return false;
});
I have a form which loads within a fancybox so that if the user clicks on a link, a form loads up in fancybox, its an #Ajax.BeginForm(). Like so:
#using (Ajax.BeginForm("AddToBasket", new { controller = "Orders" }, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SuccessBasket",
OnSuccess = "goToCheckout"
}, new { #class = "product-order-form" }))
{
#* Form elements for Model *#
<div id="SuccessBasket"></div>
}
This gets loaded up in a fancybox window. When I submit the form, my SuccessBasket div does not get updated with the new content passed from the controller, is there some way to enable Ajax calls to be updated within Fancybox? This works fine if I don't use fancybox but I wish to use it.
EDIT:
The form is loaded like so:
#Ajax.ActionLink("Order", "OrderProduct", new { controller = "Orders", id = ViewData["ID"], search = ViewData["search"] }, new AjaxOptions()
{
UpdateTargetId = "ModalWindow",
InsertionMode = InsertionMode.Replace,
OnFailure = "NotAuthorised"
}, new { #class = "lightbox order-link" })
I have an empty div called ModalWindow which is wrapped by a div set to display: none as per the instructions:
<div style="display: none">
<div id="ModalWindow">
</div>
</div>
OrderProduct Action in my controller returns a PartialView:
return PartialView("_OrderProduct", basket);
Where basket is my model BasketModel basket = new BasketModel();
My _OrderProduct PartialView is the view which contains the Ajax form at the start of my post. Which has the SuccessBasket div.
Upto this point, it works perfectly. The form loads up in fancybox.
The AddToBasket Action returns a PartialView:
return PartialView("_BasketSuccess");
This view simply tells the user that their item was added to the basket:
<p>This item has been added to your basket. Search again or goto #Html.ActionLink("checkout", "Order", new { controller = "Orders" }, new { #class = "checkout-link" }) to continue.</p>
The problem is, the SuccessBasket div does not update with the text above but through debugging, I can see that it does load the view _BasketSuccess, it just doesn't update in the modal window.
The way you are loading the fancybox is strange. You are sending 2 AJAX requests: one for the Ajax.ActionLink and one by the fancybox. All that is not necessary. Also you don't need a hidden div in your main view, the fancybox does all this automatically.
So to recap, in your main view all you need is a simple HTML link to the controller actin which will return a partial containing the form:
#Html.ActionLink("Order", "OrderProduct", "Orders", null, new { #class = "lightbox" })
and in a separate javascript file you will attach the fancybox to this anchor so that when it is clicked it will automatically send an AJAX request (the fancybox, not you), fetch the partial form and show it:
$(function () {
$('.lightbox').fancybox();
});
Alright, now you have a partial form shown in a fancybox. This partial form is actually an Ajax.BeginForm. So when you submit this form it will send an AJAX request to the AddToBasket action and upon success it will update the <div id="SuccessBasket"></div> which is inside this form with the result returned by this action.
I have a partial view inside a div with id 'rating'. So I have a ajax link inside the same partial view. So when I click on the link its updating one time and if i click the link second time, its loading the div two times and clicking three times load multiple times.
Anybody have the same issue?
<div class="rating">
#Ajax.ActionLink("Flag this review as inappropriate", "CourseRatingFlag", "Content", new { cID = Model.courseRatings[index].crid}, new AjaxOptions() { HttpMethod = "POST",TargetId="rating" })
some content...
</div>
There is a similar question here.
In my case, I resolved it locating the target div out of the partial view.