I have many select queries on my Page and few Action links based on them used gets another data tab wise.
Example on stack over flow when we see the profile of the user we see
summary questions answers tags badges etc.
If a user clicks on any one of the tab it hits the entire action and all the other sections of the pages hits the database which results in increase in load time of the page.To improve the performance I thaught to apply ajax,so after searching I got this example.
Partial View.
#model IEnumerable<AJAX.Models.tblStudent>
<table>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Age)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
<h2>Time is #DateTime.Now</h2>
Controller
public ActionResult Index()
{
return View();
}
public PartialViewResult Twenty()
{
var result = from r in db.tblStudents where r.Age == 20 select r;
return PartialView("_Country", result);
}
public PartialViewResult TwentyFive()
{
var result = db.tblStudents.Where(x => x.Age >= 25);
return PartialView("_Country", result);
}
Index View
#{
ViewBag.Title = "Home Page";
}
#Ajax.ActionLink("Age 20", "Twenty", new AjaxOptions
{
UpdateTargetId = "StudentList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
#Ajax.ActionLink("Age 25", "TwentyFive", new AjaxOptions
{
UpdateTargetId = "StudentList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
<div id="StudentList"></div>
<h2>Time is #DateTime.Now</h2>
#section scripts{
#Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
}
This works fine and have added date time to cross check whether the clicked page hits the database leaving the other sections of the page.Would like to know whether its a correct way of using Ajax in MVC. As have Ajax.ActionLink.
Note : this tutorial
it up to your application situation. You can see this post just i found.
In the amount of code you have to write (less with Ajax.ActionLink) and the level of control you need (more with Html.ActionLink and a jquery ajax call).
So it's amount of code vs level of control and functionality needed => up to you to decide which one you need.
Both approaches are perfectly fine. The Ajax.ActionLink uses the jquery.unobtrisuve-ajax script to AJAXify the anchor behind the scenes.
Personally I always use Html.ActionLink + jQuery.
collectted. See this links
link1
link2
link3
Related
My first ever Ajax request is failing, and I'm not quite sure as to why.
I've used the MVC scaffolding in order to create a table (which uses a default #Html.Actionlink). However, I'm looking to include an 'edit' section on the same page via ajax requests.
So my table now has:
<td>
#Ajax.ActionLink("Edit", "Edit", new { id=item.OID}, new AjaxOptions {
UpdateTargetId = "editblock",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET" }
) |
As suggested here.
Within the same view i have a div defined as:
<div id="editblock">
Edit Section Here
</div>
And My controller is defined as:
public PartialViewResult Edit(int? id)
{
if (id == null)
{
return PartialView(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
}
TableModel tablevar = db.TableModel.Find(id);
if (tablevar == null)
{
return PartialView(HttpNotFound());
}
return PartialView("Edit", tablevar );
}
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult Edit( TableModel tablevar )
{
if (ModelState.IsValid)
{
db.Entry(tablevar ).State = EntityState.Modified;
db.SaveChanges();
}
return PartialView("Edit",tablevar );
}
My "Edit.cshtml" looks like:
#model Project.Models.TableModel
<body>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
Could anyone suggest as to why this is failing, and what I should be doing instead to render this partial view onto the page (as currently it keeps redirecting to new page and not showing on 'index' screen)?
Place those scripts at the bottom of your view. By the time they execute your form isn't present (and therefore the auto-wireup fails). In general, you want <script> tags as close to the </body> tag as possible to your content is there before the script executes.
Other than that, you look fine.
I have an issue with a partialview, for some reason when I do a Post on it; it gives me another copy of my form; how can I make that behavior go away . This is what that partialview looks like:
// this is all inside my partialview
<div style=" float:left;">
#using (Ajax.BeginForm("posting", "post", null, new AjaxOptions
{
UpdateTargetId = "glober",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}))
{
// taken out
}
</div>
<div id="glober">
#foreach (var item in Model.Mymodel)
{
}
</div>
as you can see this is a POST and I only want to update the part with the id of "glober" which it does but for some reason when I do the post it also gives me a second copy of the form elements. If inside my ajax form I have 1 textbox called firstname then after submitting it I get 2 textboxes that says firstname, any help would be great.
Part of my controller is this were i call out the partial
var iefeeds = sqlConnection.Query<thread>("Select * from postings").ToList();
return PartialView("_mypartial");
I think you have returned View rather than PartialView in the controller. So you'll see 2 pages overlapping in response of ajax Post.
I have an view in MVC3 Razor view engine like following image. Now i want to Confirm Connection Action Output show under this link text not New page. How can i done this work?
Please explain with example code.
My View Like this :
#model ESimSol.BusinessObjects.COA_ChartsOfAccount
#{
ViewBag.Title = "Dynamic Account Head Configure";
}
<h2>Dynamic Account Head Configure</h2>
<table border="0">
<tr>
<td> Select an Server Connection </td>
<td style="width:5px">:</td>
<td>#Html.DropDownListFor(m => m.DBConnections, Model.DBConnections.Select(x => new SelectListItem() { Text = x.ConnectionName, Value = x.DBConnectionID.ToString()}))</td>
</tr>
<tr>
<td> </td>
<td style="width:5px"></td>
<td>#Html.ActionLink("Confirm Connection", "ConformConnection")</td>
</tr>
</table>
AND My Controller action Like following :
public ActionResult ConfirmConnection()
{
return PartialView();
}
I'm a big fan of using jquery and ajax for this kind of thing ...
http://api.jquery.com/jQuery.ajax/
If you are following the typical MVC model then you can add an action link to the page using something like ...
#Html.ActionLink("controller", "action", args);
but I would go for the ajax driven approach ...
<script type="text/javascript">
var ajaxBaseUrl = '#Url.Action("yourController", "ConformConnection", new { args })';
$(link).click(function () {
var currentElement = $(this);
$.ajax({
url: ajaxBaseUrl,
data: { any other queryString stuff u want to pass },
type: 'POST',
success: function (data) {
// action to take when the ajax call comes back
}
});
});
});
</script>
First move your markup to a partial view. After that define an action method that renders your partial view.
[ChildActionOnly]
public ActionResult ConfirmConnection(COA_ChartsOfAccount model)
{
return PartialView("MyPartialView", model);
}
ChildActionOnly attribute makes sure this action method cannot be called by a HTTP request.
Then you can display it whenever you want using Html.Action method.
#Html.Action("ConfirmConnection", "MyController", new { model = Model })
Ignore passing the model as a parameter if it doesn't change by the page you display it. You can retrieve it in your action method.
I ask a similar question here
So I add Some OnComplete Functions and Id to Ajax Forms, And there is:
This is My View:
#foreach(var item in Model) {
<tr id="TR#(item.Id)">
#{Html.RenderPartial("_PhoneRow", item);}
</tr>
}
_PhoneRow:
#model PhoneModel
#using(Ajax.BeginForm("EditPhone", new { id = Model.Id }, new AjaxOptions {
UpdateTargetId = "TR" + Model.Id,
OnComplete = "OnCompleteEditPhone"
}, new { id = "EditAjaxForm" + Model.Id})) {
<td>#Html.DisplayFor(modelItem => Model.PhoneNumber)</td>
<td>#Html.DisplayFor(modelItem => Model.PhoneKind)</td>
<td><input type="submit" value="Edit" class="CallEditPhone" id="edit#(Model.Id)" /></td>
}
Controller:
public ActionResult EditPhone(long Id) {
//Get model by id
return PartialView("_EditPhoneRow", model);
}
public ActionResult SavePhone(PhoneModel model) {
//Save Phone, and Get Updatet model
return PartialView("_PhoneRow", model);
}
_EditPhoneRow
#model PhoneModel
#using(Ajax.BeginForm("SavePhone", new { id = Model.Id }, new AjaxOptions {
UpdateTargetId = "TR" + Model.Id,
OnComplete = "OnCompleteSavePhone"
})) {
<td>#Html.EditorFor(modelItem => Model.PhoneNumber)</td>
<td>#Html.EditorFor(modelItem => Model.PhoneKind)</td>
<td><input type="submit" value="Save" class="SaveEditPhone" id="save#(Model.Id)" /></td>
}
And Oncomplete Scripts:
function OnCompleteEditPhone() {
$('input.SaveEditPhone').click(function () {
var id = $(this).attr("id").substring(4);
$('form#SaveAjaxForm' + id).trigger('submit');
});
}
function OnCompleteSavePhone() {
$('input.CallEditPhone').click(function () {
var id = $(this).attr("id").substring(4);
$('form#EditAjaxForm' + id).trigger('submit');
});
}
So Click Edit Worked perfect, Then Click Save Worked good also, But in second time when i click the Edit Button I have an Error in Post Action I copy the Firebug console here:
http://Mysite/members/editphone/7652 200 OK 582ms
http://Mysite/members/savephone/7652 200 OK 73ms
http://Mysite/members/editphone/7652 500 internal server error 136ms
<title>The view 'EditPhone' or its master was not found or no view engine supports the searched locations. The following locations were searched: ...
So where is the problem? If I remove OnCompleteSavePhone The Edit button for second time not worked, and with this function I have an error that not make any sense, How Can I fix it? I actually load partial views by Ajax, And need the buttons of this views worked correctly, at first every thing is fine but after Ajax result They don't, I think to add some Oncomplete functions, but there is an error also.
Your previous question is answered now. You had broken markup. As a consequence of this you no longer need to care about any OnComplete events and doing some auto triggers, form submissions and stuff. This will be handled by the Ajax.BeginForm infrastructure automatically for you.
I am aware of the previous two questions which talk about nesting partial views but the solutions don't work for my design (which might not be the best one but I'm unsure how to adapt it).
Background:
I collect questionnaire responses from users and store them on an sql server as xml files.
I have a partial view which loads a table with all the Responses of a given user, this partialview populates the table with things like Response date, link to xml response document, questionnaire name, link to xml questionnaire document (the questionnaire info is pulled from a different table) and an Ajax ActionLink which redirects to action which parses the two relevant xml documents to print out Question and Answer list (i.e. visualise the response to be human readable) inside the second partial view.
The first partial view contains a div underneath the table which I wish to populate onclick of the Ajax.ActionLink with the second partial view.
Problem:
The answers are rendered correctly however the partial view is loaded into a whole new page, without any styling.
The other solutions to this nesting problem use RenderPartial() however I use return PartialView()
Code:
First Partial View:
<table>
<thead>
<tr><th>headers with other info</th>
<th>Display(/th>
<tr>
</thead>
<tbody>
<tr><td>cells with other info</td>
<td>#Ajax.ActionLink("View", "DisplayResponse","HealthStatus", new { respID = item.UniqueID,qVersion=item.QuestionnaireVersion, qname = item.QuestionnaireName }, new AjaxOptions { UpdateTargetId = "responseDisp" })</td>
</tbody>
</table>
<div id="responseDisp"></div> <--- **This is the div I wish to populate, does anyone know why it's not working?**
DisplayResponse Action (without the logic for parsing the xml documents)
public ActionResult DisplayResponse(Guid respID, int qVersion, String qname) {
var allResponses = ZData.Responses;
var response = (from r in allResponses
where r.UniqueID == respID
select r
).First();
//geting an XML questionnaire document
var questionnaireDetails = ZodiacData.Questionnaires;
var questionnaire = (from q in questionnaireDetails
where q.Name == qname && q.Version == qVersion
select q
).First();
//creating XMLDocument to read the questionnaire
XmlDocument xqdoc = new XmlDocument();
xqdoc.LoadXml(questionnaire.Xml);
XmlElement qroot = xqdoc.DocumentElement;
ViewBag.qroot = qroot;
XmlDocument xrdoc = new XmlDocument();
xrdoc.LoadXml(response.Raw);
XmlElement rroot = xrdoc.DocumentElement;
ViewBag.rroot = rroot;
return PartialView("_PrintedResponse");
}
I would be grateful for any help!
In MVC3 the #AJax. helpers are rendering regular form and a tags with some extra data- attributes. To make the magic work some Javascript is needed which will use this generated data- attributes to make the necessary jQuery ajax calls.
These js functions are living in the jquery.unobtrusive-ajax.js so add this line to your layout or view and it should work:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"
type="text/javascript"></script>
First, as mentioned above, you must have a reference to the jquery.unobtrusive-ajax.js file as this will get things "wired" up correctly for you.
This answer is also in response to your comment on your question about how you're passing your models to your views. You are actually making things more complicated for yourself by using the ViewBag for your model.
By using the ViewBag for your models, you will have a harder time finding/fixing/resolving issues in typo's as well as the great features of the Razor helpers. The ViewBag is a dynamic object and there are no compile time type checks. You don't need to cast your objects either (less code).
The preferred (and best practice) is to hook things up like so:
1) Your controller contains ViewModels (Strongly Typed) that are passed to the ViewModels
Controller
public ActionResult Something() {
return View();
}
public ActionResult UserView() {
UserViewModel mdoel = new UserViewModel {
Email = "me#somewherecool.com",
FirstName = "Your",
SStatuses = new List<SStatus>{
new SStatus {
ID = 0
}
}
};
return PartialView("_SomethingPartial", mdoel);
}
Index ("Something" view)
#{
ViewBag.Title = "Something";
}
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<h2>Something</h2>
#Ajax.ActionLink("Ajax Click", "UserView", new AjaxOptions { UpdateTargetId = "MyDivContainer", InsertionMode = InsertionMode.Replace })
<div id="MyDivContainer">
<!-- my content should be here -->
</div>
Partial View
#model StackModels.UserViewModel
<div class="par">
#Html.LabelFor(m => m.FirstName)
<div class="field">
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
</div>