POST method with AJAXOption in MVC3 call GET request - asp.net-mvc-3

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

Related

Ajax Beginform Parameters

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 .

Data not going to controller using Ajax

I am new to AJAX and I am trying to send some data to the controller using the AJAX. on clicking the button "Start Event", nothing is happening..
This is my jsp page where I have written the AJAX code
<c:forEach items="${scheduledEvents}" var="event">
<div class="col-md-3" id="eventId">
<div class="card-counter primary">
<div id="head" class="card-counter head-color"></div>
<span class="count-head">${event.eventName}</span>
<br>
<span class="count-name">Date : ${event.date}</span>
<span class="count-name">Location : ${event.location}</span>
<span class="count-name">Hosted By : ${event.hostName}</span>
<span class="count-name">Description : ${event.description}</span>
<br>
<br>
<div class="count-join">
<button class=" btn" id="${event.linkId}" style="background-color: #cc3300;"><font style="color: white;">Start Event</font></button>
</div>
</div>
</div>
</c:forEach>
<script type="text/javascript">
$(function() {
$('.count-join').on('click',function(){
var eventData = $(this).attr("id")
.ajax({
url : 'startEvent?data=' +eventData,
type : 'GET',
contentType : 'application/json',
success : function(data){
$
.get(
'${pageContext.request.contextPath}/startEvent',
function(data,status) {
$("#eventId").html(data);
}
);
}
});
});
});
</script>
And this my controller mapping
#RequestMapping(value="/dashBoard/startEvent")
public ModelAndView startScheduledEvent(#RequestParam("data")String data)
{
System.out.println(data);
return new ModelAndView("DashBoard");
}
Where am I wrong? please give some detailed explanation as I do not know much about AJAX. Thanks in advance.
As per you controller #RequestMapping, you have missed the /dashBoard in ajax call.

Refresh g:each tag via AJAX call in Grails

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])
}

how to update 2 text fields on click of a search button in the same form by fetching data from Grails Controller using AJAX in Grails 2.1.0

I have a controller(SearchController) which fetches data on clicking a search button (inside myview.gsp) i want to populate 2 text fields present in the same myview.gsp with the data i have in my controller (SearchController) .I know i need to do ajax calling because i want to populate only 2 fields and dont want to reload the page which contains other valuable information . How can i achieve it please guide me
here is my Controller
def searchItem() {
def itemFound = MyService.searchP20Code(params["item"])
def resultMap = [:]
if (itemFound!=null)
{
resultMap.put("CODE",itemFound[1])
resultMap.put("DESC",itemFound[2])
}
println "Result:"+resultMap
session.setAttribute("searchResult", resultMap)
render(view: myview" )
}
myview.gsp
myview.gsp
<div class="leftPanel filter-label">
<a href="#" class="tt"> <g:message
code="Normal.label.Code" />
</a>
</div>
<div class="rightPanel filter-field-wrapper">
<input type="text"
name="Code" maxlength="30"
value=""
id="i_code" />
</div>
</div>
<div class="formLables">
<div class="leftPanel filter-label">
<a href="#" class="tt"> <g:message
code="Normal.label.Description" />
</a>
</div>
<div class="rightPanel filter-field-wrapper">
<input type="text"
name="Desc" maxlength="30"
onkeyup="fieldMaxlength('material_code')" value=""
id="i_description" />
</div>
</div>
<g:actionSubmit
value="${message(code:'Normal.button.search', default: 'Search Code')}"
action="searchItem" />
please help my how can i update only these two text fields in myview.gsp onclicking search button using ajax .I am using grails 2.1.0
Here you can find a detailed example with Grails build-in Ajax support.
You can also use JQuery (example here)
EDIT:
Your controller needs to look like this:
import grails.converters.JSON
class ExampleController {
....
def searchItem() {
def itemFound = MyService.searchP20Code(params["item"])
def resultMap = [:]
if (itemFound!=null) {
resultMap.put("CODE",itemFound[1])
resultMap.put("DESC",itemFound[2])
}
println "Result:"+resultMap
//session.setAttribute("searchResult", resultMap)
render(resultMap as JSON )
}
}
and your gsp
<head>
...
<g:javascript plugin="jquery" library="jquery" src="jquery/jquery-{WRITE_YOUR_VERSION_HERE}.js"/>
<script>
function callAjax(e){
e.preventDefault();
$.ajax({
url: "example/search",
type:"post",
dataType: 'json',
success: function(data) {
console.log(data);
$("input[name='Code']").val(data.CODE);
$("input[name='Desc']").val(data.DESC);
}
});
}
</script>
...
</head>
<body>
....
<input type="submit" value="Call Ajax Function" onclick="callAjax()">
....
</body>

ASP.NET MVC4 PartialView Not Being Rendered Inside Parent View

I'm trying to filter a list of entities and update the partial view on the page with the filtered data. The partial view is returning the correct model with the filtered data, but is not being rendered inside the parent page. Instead it is being rendered in "body" element of an empty HTML page. I've found many topics on this but even though I appear to be following their directions, I'm still having no luck. A fresh set of eyes from the community here may be a huge help.
#model PennLighting.ViewModels.LinecardViewModel
#{
ViewBag.Title = "Linecard";
}
<div class="linecard-head">
#using (Ajax.BeginForm("Index",
new AjaxOptions
{
UpdateTargetId = "linecard"
}))
{
#Html.EditorFor(model => model.Categories)
<div class="buttons">
<input type="submit" name="btnFilter" value="Filter" />
<input type="submit" name="btnShowAll" value="Show All" />
</div>
}
</div>
<div id="linecard">
#Html.Partial("Linecard")
</div>
#section Scripts
{
#Scripts.Render("~/bundles/jqueryval")
}
public ActionResult Index()
{
var viewModel = new LinecardViewModel();
viewModel.Categories = db.Categories
.OrderBy(c => c.Name).ToList();
viewModel.Manufacturers = db.Manufacturers
.OrderBy(m => m.Name).ToList();
return View(viewModel);
}
public ActionResult Index(string btnFilter, string[] selectedCategories)
{
var viewModel = new LinecardViewModel();
var selectedMfrs = new List<Manufacturer>();
if (btnFilter != null && selectedCategories != null)
{
var categoryIds = selectedCategories.Select(c => int.Parse(c)).ToArray();
if (categoryIds != null)
{
selectedMfrs = db.Manufacturers
.Where(m => m.Categories.Any(c => categoryIds.Contains(c.ID)))
.OrderBy(m => m.Name).ToList();
}
}
else
selectedMfrs = db.Manufacturers.OrderBy(m => m.Name).ToList();
viewModel.Manufacturers = selectedMfrs;
return PartialView("Linecard", viewModel);
}
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/themes/base/css", "~/Content/css")
</head>
<body>
<div id="container" class="round-bottom">
<div id="header">
<div id="header-left">
<div id="logo">
<a href="#Url.Content("~/")">
<img src="#Url.Content("~/Content/Images/logo.png")" alt="Penn Lighting Associates" /></a>
</div>
</div>
<div id="header-right">
<ul class="nav">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("About", "Index", "About")</li>
<li>#Html.ActionLink("Linecard", "Index", "Linecard")</li>
<li>#Html.ActionLink("Events", "Index", "Events")</li>
<li>#Html.ActionLink("Gallery", "Index", "Gallery")</li>
<li>#Html.ActionLink("Contact", "Index", "Contact")</li>
<li><a href="http://oasis.pennlighting.com:81/OASIS/desk/index.jsp" target="_blank">
Customer Login</a></li>
</ul>
</div>
</div>
<div id="main">
#RenderBody()
</div>
</div>
<div id="footer">
<p>
Copyright © 2008 Penn Lighting Associates</p>
</div>
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts",false)
</body>
</html>
So what am I missing? Thanks!
You cannot have 2 actions on the same controller with the same name accessible on the same HTTP verb. You might want to decorate your Index contorller action that is invoked with an AJAX call and returns a partial with the [HttpPost] attribute:
[HttpPost]
public ActionResult Index(string btnFilter, string[] selectedCategories)
{
...
}
Without seeing more of your solution, it's a bit fuzzy, but I believe you want to still return the Index and pass the model data into the Partial in your view. The way you are doing it would return only the partial view, which is why you're getting those results.
So in the filtered index:
return View(viewModel)
And in the index view, pass the data to the partial, which I assume without seeing has the right model association to display.
UPDATE
If you're looking to dynamically pull a subset of data and leave the rest untouched, then do an AJAX POST with the filter information to the action specified for the partial view. Take the data results and place them in the Linecard div.
There are many ways to send the data (bundle by JSON, serialize form, individual data points). Here are some examples:
http://brandonatkinson.blogspot.com/2011/01/using-jquery-and-aspnet-mvc-to-submit.html
MVC ajax json post to controller action method
The problem was that my jqueryval bundle was missing the jquery.unobtrusive-ajax.js file. My code works as is once that was included.

Resources