How to avoid rendering entire page when using CGridView via AJAX - yii

When creating any ajax request in yii CGridView like (pagination, filtering, ...etc) the result of request will render whole page, how can i avoid that?
I tried to use renderPartial for view but it doesn't work. if this is the solution, how can i do it?
I just need to render the table of GridView not whole page.
Please advice.

In controller:
$this->layout = false;
For me works also $this->renderPartial() in controller instead of $this->render()
if(Yii::app()->request->isAjaxRequest()) $this->renderPartial('view');
else $this->render('view');
U can create class:
class Controller extends CController {
public function beforeAction($action) {
if(Yii::app()->request->isAjaxRequest) $this->layout = false;
return parent::beforeAction($action);
}
}

Related

How to get a url after returning the view?

I am new to MVC4, I am using more then one form in one View. When i am posting the form i am getting all the formcollecion values in controller. When i am returning the different view also, its working fine. My problem is after returning view, the url showing that post method name.when i try to refresh this page its showing error.
Initially the url was : Admin/Activities
after posting the form : Admin/UpdateActivity
I need url like this after returning the view : Admin/Activities
how to get it, Please help me. Thanks in advance.
I dont have any separate view for this ActionResult. This is my code:
[HttpPost]
public ActionResult UpdateActivity(FormCollection coll)
{
................
ViewBag.updateAlert = "Activity updated sucessfully";
return View("Activities");
}
#using (Html.BeginForm("UpdateActivity", "Admin", FormMethod.Post,new { #id = "formID" }))
Change your form attribute as it. It will automatically return to the view Activities.
Note: if your form on Admin/Activities.
After updating the record,you can Redirect to that action,instead of returning the same view again, and instead of ViewBag you will have to use TempData as ViewBag will be null after redirecting:
[HttpPost]
public ActionResult UpdateActivity(FormCollection coll)
{
................
TempData["updateAlert"] = "Activity updated sucessfully";
return RedirectToAction("Activities","Admin");
}

i want to show data on form fields using id with ajax

how i use ajax in yii to show result against id??
public function actionView(){
$model= new ViewForm();
$model->unsetAttributes();
if (isset($_GET['ViewJob'])) {
$model->attributes = $_GET['ViewJob'];
}
$this->render('viewjob',array(
'model'=>$model
));
}
Please clarify you question.. If you are looking for how to use ajax in Yii then this might help u.
http://www.yiiframework.com/wiki/394/javascript-and-ajax-with-yii/
http://www.yiiframework.com/wiki/49/update-content-in-ajax-with-renderpartial/
http://www.yiiframework.com/wiki/388/ajax-form-submiting-in-yii/

Yii: How to force CGridview to load data via AJAX only?

Is there a way to make a CGridView Not load data on the initial rendering of the view it lives on, and instead make it load the first page with a subsequent AJAX request after the initial page load?
This is mostly for performance optimization. There is a data model that is rather slow behind that CGridView, and I would like to be able to have the page load in a snappy way, then have the data load up a few seconds later with an AJAX request.
You could modify the action as follows:
public function actionIndex() {
$dataProvider = new CActiveDataProvider('User'); // The dataprovider your grid uses
if (!$this->isAjaxRequest()) {
$dataProvider->criteria->addCondition('1 = 0'); // You could also use 0, but I think this is more clear
}
[...]
}
And then in your view in the javascript section:
$(function() { // If you are using jQuery this is executed when the page is loaded
$.fn.yiiGridView.update("{id-of-your-grid-view}");
});
Brewer Gorge was very close, and thanks to his suggested answer, it put me on the right track. This works:
// Controller, after creating $dataProvider, before calling $this->render...
if (!Yii::app()->request->isAjaxRequest) {
$dataProvider->criteria->addCondition('1 = 0');
}
// View
<script type="text/javascript">
$(window).load(function() {
$('#id-of-grid').yiiGridView('update');
});
</script>
Just write your code in controller like this:
$model= new Data('search');
$model->unsetAttributes();
if(isset($_GET['Data']))
$model->attributes = $_GET['Data'];
if (!Yii::app()->request->isAjaxRequest)
$data->id=0; //or something that sure model return empty

unobtrusive validation not working with dynamic content

I'm having problems trying to get the unobtrusive jquery validation to work with a partial view that is loaded dynamically through an AJAX call.
I've been spending days trying to get this code to work with no luck.
Here's the View:
#model MvcApplication2.Models.test
#using (Html.BeginForm())
{
#Html.ValidationSummary(true);
<div id="res"></div>
<input id="submit" type="submit" value="submit" />
}
The Partial View:
#model MvcApplication2.Models.test
#Html.TextAreaFor(m => m.MyProperty);
#Html.ValidationMessageFor(m => m.MyProperty);
<script type="text/javascript" >
$.validator.unobtrusive.parse(document);
</script>
The Model:
public class test
{
[Required(ErrorMessage= "required field")]
public int MyProperty { get; set; }
}
The Controller:
public ActionResult GetView()
{
return PartialView("Test");
}
and finally, the javascript:
$(doument).ready(function () {
$.ajax({
url: '/test/getview',
success: function (res) {
$("#res").html(res);
$.validator.unobtrusive.parse($("#res"));
}
});
$("#submit").click(function () {
if ($("form").valid()) {
alert('valid');
return true;
} else {
alert('not valid');
return false;
}
});
The validation does not work. Even if I don't fill any information in the texbox, the submit event shows the alert ('valid').
However, if instead of loading dynamically the view, I use #Html.Partial("test", Model) to render the partial View in the main View (and I don't do the AJAX call), then the validation works just fine.
This is probably because if I load the content dynamically, the controls don't exist in the DOM yet. But I do a call to $.validator.unobtrusive.parse($("#res")); which should be enough to let the validator about the newly loaded controls...
Can anyone help ?
If you try to parse a form that is already parsed it won't update
What you could do when you add dynamic element to the form is either
You could remove the form's validation and re validate it like this:
var form = $(formSelector)
.removeData("validator") /* added by the raw jquery.validate plugin */
.removeData("unobtrusiveValidation"); /* added by the jquery unobtrusive plugin*/
$.validator.unobtrusive.parse(form);
Access the form's unobtrusiveValidation data using the jquery data method:
$(form).data('unobtrusiveValidation')
then access the rules collection and add the new elements attributes (which is somewhat complicated).
You can also check out this article on Applying unobtrusive jquery validation to dynamic content in ASP.Net MVC for a plugin used for adding dynamic elements to a form. This plugin uses the 2nd solution.
As an addition to Nadeem Khedr's answer....
If you've loaded a form in to your DOM dynamically and then call
jQuery.validator.unobtrusive.parse(form);
(with the extra bits mentioned) and are then going to submit that form using ajax remember to call
$(form).valid()
which returns true or false (and runs the actual validation) before you submit your form.
Surprisingly, when I viewed this question, the official ASP.NET docs still did not have any info about the unobtrusive parse() method or how to use it with dynamic content. I took the liberty of creating an issue at the docs repo (referencing #Nadeem's original answer) and submitting a pull request to fix it. This information is now visible in the client side validation section of the model validation topic.
add this to your _Layout.cshtml
$(function () {
//parsing the unobtrusive attributes when we get content via ajax
$(document).ajaxComplete(function () {
$.validator.unobtrusive.parse(document);
});
});
test this:
if ($.validator.unobtrusive != undefined) {
$.validator.unobtrusive.parse("form");
}
I got struck in the same problem and nothing worked except this:
$(document).ready(function () {
rebindvalidators();
});
function rebindvalidators() {
var $form = $("#id-of-form");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse($form);
$form.validate($form.data("unobtrusiveValidation").options);
}
and add
// Check if the form is valid
var $form = $(this.form);
if (!$form.valid())
return;
where you are trying to save the form.
I was saving the form through Ajax call.
Hope this will help someone.
just copy this code again in end of modal code
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
;)

Generating a modal jQuery partial view with MVC4 does not work

I like the way MVC4 manage the new logon screen: it is possible to have a modal dialog showed.
I tried to reproduce the same behavior in the same solution for another view. But it doesn't work because Request.QueryString["content"] is null. I don't know why. In fact, there is an action method called ContextDependentView (generated by the MVC template) where the trick occurred. Here it is:
private ActionResult ContextDependentView()
{
string actionName = ControllerContext.RouteData.GetRequiredString("action");
if (Request.QueryString["content"] != null)
{
ViewBag.FormAction = "Json" + actionName;
return PartialView();
}
else
{
ViewBag.FormAction = actionName;
return View();
}
}
If the value of Request.QueryString["content"] is not null then we display a partial view (modal jQuery) otherwise it is a classic view.
Can someone help me understand why this is not working?
PS: another thread already exists but without any solution.
The login and register links are bound to a click handler in AjaxLogin.js which then adds content=1 in loadAndShowDialog