I am not getting how to pass my image names form view to action method .I am using ajax Beginform .The problem is,if I don't use ajax beginform ,So much of code changes are required.
'#using (Ajax.BeginForm("postvalue","MyController",new (imagecount="count" new AjaxOptions {
HttpMethod="POST", OnBegin = "getValues" }))
{
<div id="preview">`enter code here`
<div id="1">
<label>image1</label>
</div>
<div id="2">
<label>image2</label>
</div>
</div>
</div>
}'
How can I be able to assign a value to image count .
Related
I have a statistical panel which displays the last registered users. I want to implement a AJAX call to upload the panel without having to reload the full page.
I have the following code in my view:
<g:each in="${lastUsers}" var="user">
<div class="mt-comments">
<div class="mt-comment">
<div class="mt-comment-img">
<g:if test="${user?.avatar}">
<img src="${createLink(controller:'controllerUser',
action:'image', id: user?.id)}" />
</g:if>
<g:else>
<img class="img-circle"
src="${resource(dir: 'img/profile', file: 'user_profile.png')}"/>
</g:else>
</div>
<div class="mt-comment-body">
<div class="mt-comment-info">
<span class="mt-comment-author">${user?.username}</span>
<span class="mt-comment-date">
<g:formatDate date="${user?.dateCreated}"/>
</span>
</div>
<div class="mt-comment-text">${user?.email}</div>
<div class="mt-comment-details">
<g:if test="${user?.enabled}">
<span class="mt-comment-status label label-sm label-success circle">
</g:if>
<g:else>
<span class="mt-comment-status label label-sm label-info circle">
</g:else>
<g:formatBoolean boolean="${user?.enabled}"/>
</span>
<ul class="mt-comment-actions">
<li>
<g:link controller="user" action="edit" id="${user?.id}">Edit</g:link>
</li>
</ul>
</div>
</div>
</div>
</div>
</g:each>
Also, I have a button when it is clicked calls the AJAX function. The Ajax function receives the data successful in JSON format. From there, I don't know upload my g:each tag.
I have tried the remoteFunction of Grails to use the upload attribute, but an error appears: No javascript provider is configured and I have searched the solution but anything works me.
The AJAX call:
$('.button').click(function() {
$.ajax({
url: URL,
success: function(data) {
console.log(data[index]);
console.log(val.username);
console.log(val.dateCreated);
console.log(val.email);
console.log(val.enabled);
console.log(val.avatar);
console.log(val.id);
},
error: function(){
},
});
Thanks for helping me.
Instead of Using JSON Data, You can do this using grails templates and jQuery load method. Here is a quick POC.
Template (_userComments.gsp)
This will act as a reusable view which can be called via AJAX or can be included directly in other views.
<g:each in="${lastUsers}" var="user">
<div class="mt-comments">
.....
</div>
</g:each>
View (main.gsp)
Our Main View.
<div class="userComments">
<!-- When the Page is Loaded, We need render this without an Ajax Call -->
<g:render template="userComments" model="['lastUsers':lastUsers]"/>
</div>
Javascript
$('.button').click(function() {
$( ".userComments" ).load( "user/userComments" );
});
Controller
We are defining two methods one for the main view and one for the ajax call.
def index() {
def lastUsers = User.list();
render(view:'main', model: [lastUsers: lastUsers])
}
// Ajax Call
def userComments() {
def lastUsers = User.list(); // what ever your fetch logic is
render(template:'userComments', model: [lastUsers: lastUsers])
}
Within a view I am trying to load a partial view from the controller. I am using the Ajax.ActionLink method to make this call
#Ajax.ActionLink("Involved Entities/Resources",
"GetNarratives",
new { id = 4 },
new AjaxOptions { HttpMethod = "GET",
UpdateTargetId = "narrContainer" })
Further down in the page I have a div element with the id of narrContainer
<div id="narratives" class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title"><a data-toggle="collapse" href="#collapseNarrative">Narratives [ #Model.AssociatedNarrative.Count() ]</a></h4>
</div>
<div id="collapseNarrative" class="panel-collapse collapse">
<div class="panel-body">
<div id="narrContainer"></div>
</div>
</div>
</div>
</div>
</div>
The controller has the following code:
public PartialViewResult GetNFIRNarratives(string id)
{
//Get Narratives
fauxModel fm = new fauxtModel();
List<Narrative> narr = new List<Narrative>();
narr = fm.GenerateMockBaseNarratives(4);
return PartialView("_myAssociatedNarrative", narr);
}
The partial view contains fields for the collection:
<!-- Assocaited Narrative-->
#for (int i = 0; i < #Model.Count(); i++)
{
<div class="col-md-12">
<p><strong>Date Entered</strong> #Html.DisplayFor(x => x[i].DateEntered)</p>
</div>
if (!string.IsNullOrWhiteSpace(#Model[i].Title))
{
<div class="col-md-12">
<p><strong>Narrative Title</strong> #Html.DisplayFor(x => x[i].Title) </p>
</div>
}
<div class="col-md-12">
<p>#Html.DisplayFor(x => x[i].NarrativeText)</p>
<hr />
</div>
}
Within the base layout page I have added reference to the unobtrusive-ajax script as
<script src="#Url.Content("~/js/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
And I have confirmed that the key is enabled in the web.config file.
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
When I click on the link to load the narratives the code executes but it does not load the partial in the div element. Instead it is replacing the current view the partial. What I am missing that is causing the partial to be loaded /replacing the current document and what do I need to change to get the partial to render only within the specified div element?
After working through the Post Event more I discovered that the #Ajax.Action was not posting as an AJAX call. This was the result of the jquery-unobtrusive-ajax.js file being outdated and containing deprecated jquery functions (.live()) .
I updated the files through NuGet using
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
and the actions are now working correctly.
I have the following index view:
#model BoringStore.ViewModels.ProductIndexViewModel
#{
ViewBag.Title = "Index";
}
<h2>Produkte</h2>
<div id='addProduct'>
#{ Html.RenderPartial("Create", new BoringStore.Models.Product()); }
</div>
<div id='productList'>
#{ Html.RenderPartial("ProductListControl", Model.Products); }
</div>
The "productList" is just a list of all products.
The addProduct renders my Create View:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<div id="dialog-confirm" title="Produkt hinzufügen" style="display:none">
#using (Ajax.BeginForm("Index_AddItem", new AjaxOptions { UpdateTargetId = "productList" }))
{
#Html.Raw(DateTime.Now.ToString());
<div>
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
</div>
<br />
<div>
#Html.LabelFor(model => model.Price)
#Html.EditorFor(model => model.Price)
</div>
<br /><br />
<div>
<input type="submit" value="Produkt hinzufügen" />
</div>
}
When submitting the form, the Index_AddItem-method in my controller is called. Unfortunately the form always calls the method twice. :(
Can someone help me out?
Don't include scripts inside your partial views! They should go the your "main" views or your _layout.cshtml.
Your problem is that you have included the jquery.unobtrusive-ajax.min.js twice in your page. Once in your Create partial and once somewhere else. Because if you include that script multiple times it will subscribe on the submit event multiple times so you will get multiple submit with a single click.
So make sure that you have include that script only once in a page. So move the jquery.unobtrusive-ajax.min.js reference into your index view.
insure that you dont have jquery.unobtrusive-ajax.min.js file duplicated in the layout
as mentioned above, and you can check this using browser Inspectors
Another problem which may cause this error that i have encountered is resting a form using jquery in the ajax request as following
$("form").trigger("reset"); //just remove this line
I am confused with AjaxOption in MVC3 , i would like to make post request but it's always make get request and redirects to new url.
my .cshtml code as per below
<div >
#Html.ActionLink("Check Availability", "ValidateUsername", "Wizard", new { username = "arun"},
new AjaxOptions()
{
Url="/Wizard/ValidateUserName",
UpdateTargetId = "msg",
HttpMethod = "POST",
LoadingElementId = "progress"
})
</div>
<div id="progress">
<img alt="" src="../../Content/Images/progress.gif" width="20px" height="20px" style="display: none" />
</div>
<div id="msg">
</div>
and controller action as per below
public ActionResult ValidateUsername(string username)
{
Thread.Sleep(200);
//return Json(!username.ToLower().Equals("arun"));
return Json(true , JsonRequestBehavior.AllowGet);
}
it's always make get request instead of POST request and redirect to new URL http://localhost:55152/Wizard/ValidateUsername?username=arun , why?
and HTML code generated as per below
<div >
<a Confirm="" HttpMethod="POST" InsertionMode="Replace" LoadingElementDuration="0" LoadingElementId="progress" OnBegin="" OnComplete="" OnFailure="" OnSuccess="" UpdateTargetId="msg" Url="/Wizard/ValidateUserName" href="/Wizard/ValidateUsername?username=arun">Check Availability</a>
</div>
<div id="progress">
<img alt="" src="../../Content/Images/progress.gif" width="20px" height="20px" style="display: none" />
</div>
<div id="msg">
</div>
You need to use #Ajax.ActionLink instead of #Html.ActionLink to post data by ajax
Anchor tags in HTML always does a get request. You should either use Jquery post.
See here for more details
I have a farily straight forward form that renders personal data as a partial view in the center of the form. I can not get client side validation to work on this form.
I started chasing down the generate html and came up with the same model field rendered on a standard form and a partial view.
I noticed that the input elements are correctly populated on the first call, #html.partial, the following only happens when the partialview is reloaded via an ajax request.
First the header of my partial view, this is within a Ajax.BeginForm on the main page.
#model MvcMPAPool.ViewModels.EventRegistration
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function ()
{
$(".phoneMask").mask("(999) 999-9999");
});
</script>
#{
var nPhn = 0;
var dTotal = 0.0D;
var ajaxOpts = new AjaxOptions{ HttpMethod="Post", UpdateTargetId="idRegistrationSummary", OnSuccess="PostOnSuccess" };
Html.EnableClientValidation( true );
Html.EnableUnobtrusiveJavaScript( true );
}
Here is the razor markup from the partial view:
#Html.ValidationMessageFor(model=>Model.Player.Person.Addresses[0].PostalCode)
<table>
<tr>
<td style="width:200px;">City*</td>
<td>State</td>
<td>Zip/Postal Code</td>
</tr>
<tr>
<td>#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].CityName, new { style="width:200px;", maxlength=50 })</td>
<td>
#Html.DropDownListFor(p=> Model.Player.Person.Addresses[0].StateCode
, MPAUtils.GetStateList(Model.Player.Person.Addresses[0].StateCode))</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].PostalCode, new { style="width:80px;", maxlength=10 })
</div>
</td>
</tr>
</table>
Here is the rendered field from the partial view:
<td>
<div class="editor-field">
<input id="Player_Person_Addresses_0__PostalCode" maxlength="10" name="Player.Person.Addresses[0].PostalCode" style="width:80px;" type="text" value="" />
</div>
</td>
Here is the same model field rendered in a standard view:
<div class="editor-field">
<input data-val="true" data-val-length="The field Postal/Zip Code must be a string with a maximum length of 10." data-val-length-max="10" data-val-required="Postal or Zip code must be provided!" id="Person_Addresses_0__PostalCode" maxlength="10" name="Person.Addresses[0].PostalCode" title="Postal/Zip Code is required" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Person.Addresses[0].PostalCode" data-valmsg-replace="true"></span>
</div>
Notice that the partial view rendering has no data-val-xxx attributes on the input element.
Is this correct? I do not see how the client side validation could work without these attributes, or am I missing something basic here?
In order to create the unobtrusive validation attributes, a FormContext must exist. Add the following at the top of your partial view:
if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
If you want the data validation tags to be there, you need to be in a FormContext. Hence, if you're dynamically generating parts of your form, you need to include the following line in your partial view:
#{ if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext(); }}
You then need to make sure you dynamically rebind your unobtrusive validation each time you add/remove items:
$("#form").removeData("validator");
$("#form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#form");