I can't seem to get a jQuery AJAX post to update a div with the returned partial view. The partial view is returned with the correct html and displays in its entirety within the browser but I cannot get it to display in the div I would like it to. I'm sure it is something rather simple but I can't seem to figure it out after numerous hours of trying to solve this.
Ultimately what I am trying to achieve is when the form is posted that the results are display in another div and I would then, somehow, update another div with another partial view via another ajax call. I have set this test up to get familiar with how things work but I am struggling to get this right.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="id,Name")] Test test)
{
if (ModelState.IsValid)
{
db.Test.Add(test);
db.SaveChanges();
return PartialView("DetailsPartial", test);
}
return PartialView("CreatePartial");
}
Main page:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
<button id="Create">Create</button>
</p>
<div id="CreatePlaceholder">
</div>
<div id="DetailsPlaceholder">
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$('#Create').click(function (event) {
event.preventDefault();
$.ajax({
type: 'get',
url: '/Test/Create'
}).done(function (data) {
$('#CreatePlaceholder').html(data)
})
})
$('#CreateForm').submit(function (event) {
event.preventDefault();
var $form = $(this);
var formData = $form.serialize;
alert(formData);
formData.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
$.ajax({
type: 'POST',
url: '/Test/Create',
data: formData,
success: function (result) {
$('#DetailsPlaceholder').html(result);
}
})
});
})
</script>
Create partial view:
#model PerformanceTools.Models.Test
<form id="CreateForm" method="post" action="#Url.Action("Create","Test")">
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Test</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
Details partial view:
#model PerformanceTools.Models.Test
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.id)
</dt>
<dd>
#Html.DisplayFor(model => model.id)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
#Html.DisplayFor(model => model.Name)
</dd>
</dl>
However you are rendering your partial view put it inside a div.
<div id="partialSummaryDiv">#{Html.RenderPartial("YourPartial");}</div>
On the success of the Ajax call call .html() on the div not on the partial view.
success: function (data) {
$('#partialSummaryDiv).html(data);
}
It is not displaying in the Div because you did not define the partial view in the div. If you want the partial view hidden until the ajax success comes through, you will need to add additional logic
The problem was that the event was never being hooked up to the forms submit due to it being added to the page after the DOM was ready.
I was able to fix the issue by using .on on the empty placeholder div.
$('#CreatePlaceholder').on('submit', '#CreateForm', function (event) {
event.preventDefault();
var formData = $(this).serialize();
formData.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
$.ajax({
type: 'POST',
url: '/Test/Create',
data: formData
}).done(function (data) {
$('#DetailsPlaceholder').html(data);
})
});
Related
I'm working on Asp.net Mvc news website like (yahoo, BBC ...).
I have loads of divs that contains the feed title,text and image.What I want to achieve is to make these divs that contains these 3 elements clickable no matter where I clicked (title,text or feed image)and to post the value of the feed ID to my controller method.
I've done this already like this:
In my feed table I have : FeedID-FeedText-FeedPath
View:
#foreach (Feeds item in Model.FeedViewModel)
{
<div class="col-4">
#using (Html.BeginForm("goToFeed", "Home"))
{
<h3>#item.title</h3>>
<button type ="submit" name="FeedID" value="#item.FeedID"
style="background:none; border:none" href="#">#item.FeedText</button>
<img src="#Url.Content(#item.FeedPath)">
}
</div>
}
And in my controller I'm taking the "FeedID"
Controller:
[HttpPost]
public ActionResult goToFeed(int FeedID)
{
//some code here
}
I guess there should be a way to post the FeedID inside this div without making it a button.
I've checked these posts already but none of them helped me.
Form submit by click on a div element without JS
submiting form on div click with js
Thanks for any help...
You should not use a POST request to read data. The correct HTTP verb in this case would be GET. POST should mainly be used to create new entries. See Using HTTP Methods for RESTful Services.
This has not only academic reasons. If you use POST, and your users use the backwards/forwards buttons of the browser to navigate, they would see "Are you sure you want to resubmit the form?" messages.
To use GET, your CSHTML could look like this. Use CSS marker classes js-feed and js-feedId so you can later access these elements using jQuery.
#foreach (Feeds item in Model.FeedViewModel) {
<div class="col-4 js-feed">
<h3>#item.title</h3>>
<span>#item.FeedText</span>
#Html.HiddenFor(m => item.FeedID, new { #class = "js-feedId" })
</div>
}
The URL to the GET action is configured in the JS part. Extract the FeedId from the clicked div, replace the placeholder in the configured URL with this FeedId, and then redirect to this action by setting window.location.href, which will reload the page.
If you do not want to reload the entire page, use $.ajax instead.
<script type="text/javascript">
$(document).ready(function() {
var getUrl = '#Url.Action("goToFeed", "Home", new { FeedID = "To_Be_Replaced_By_JS" })';
$('.js-feed').on('click', function() {
var feedId = $('.js-feedId', $(this)).val(); // search only inside clicked element
var feedUrl = getUrl.replace('To_Be_Replaced_By_JS', feedId);
window.location.href = feedUrl;
});
});
</script>
The target controller action should be attributed with [HttpGet].
[HttpGet]
public ActionResult goToFeed(int FeedID) {
//some code here
}
Change this:
#foreach (Feeds item in Model.FeedViewModel)
{
<div class="col-4">
#using (Html.BeginForm("goToFeed", "Home"))
{
<h3>#item.title</h3>>
<button type ="submit" name="FeedID" value="#item.FeedID"
style="background:none; border:none" href="#">#item.FeedText</button>
<img src="#Url.Content(#item.FeedPath)">
}
</div>
}
To this:
#foreach (Feeds item in Model.FeedViewModel)
{
<div class="feed col-4">
#using (Html.BeginForm("goToFeed", "Home"))
{
#Html.HiddenFor(m => item.FeedID)
<h3>#item.title</h3>>
<button type ="submit" name="FeedID" value="#item.FeedID"
style="background:none; border:none" href="#">#item.FeedText</button>
<img src="#Url.Content(#item.FeedPath)">
}
</div>
}
Then add this to your page:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() {
$('.feed').click(function() {
return $(this).closest("form").submit();
});
});
</script>
Having a field is required when posting a razor form to the server so having the FieldID hidden will allow this to be sent. Having a div surrounding the area adding the onclick attribute with a submit function to post the above form document.forms[0].submit() can also be used.
#foreach (Feeds item in Model.FeedViewModel)
{
<div class="col-4">
#using (Html.BeginForm("goToFeed", "Home"))
{
<div onclick="this.parentNode.submit()">
#Html.HiddenFor(m => item.FeedID)
<h3>#item.title</h3>>
<button type ="submit" name="FeedID" value="#item.FeedID"
style="background:none; border:none" href="#">#item.FeedText</button>
<img src="#Url.Content(#item.FeedPath)">
</div>
}
</div>
}
I've been working on a project recently and it requires me to POST the required name to my profile.js file, but when I do console.log(req.body.bookName) (because the data I'm sending is called bookName), it gives me the error of [Error: Query is required]
Here is the post part of my profile.js code
router.post('/', function(req, res){
if(req.session && req.session.user){
Book.find({ owner: req.session.user.username || req.session.user }, function(err, book){
if(err){
console.log(err);
}
books.search(req.body.search, options, function(error, results) {
if ( ! error ) {
console.log(req.body.bookName);
res.render("profile",{
authenticated: true,
info: books,
results: results
});
}
else {
console.log(error);
}
});
});
}
else{
res.status(401).send('You must be logged in to access this page');
}
})
Here is my button in my .ejs file
<form method="POST">
<input type="text" name="search" placeholder="Search..." required class="searchBook">
<input type="submit" value="Search">
</form>
<% for(var i = 0; i < results.length; i++){ %>
<div class="ui grid">
<div class="column four wide">
<div class="ui card">
<div class="image">
<img src = "<%= results[i].thumbnail %>"/>
</div>
<div class="content">
<div class="header">
<h1 class="ui small header title"><%= results[i].title %></h1>
</div>
<div class="meta">
<p>Author: <%= results[i].authors %></p>
<p>Published on: <%= results[i].publishedDate %></p>
<p>Pages: <%= results[i].pageCount %></p>
</div>
</div>
<div class="content extra">
<button id="detail" class="<%= results[i].title %>">View Detail</button>
<button class="ui button fluid" type="button" name="button">Add</button>
</div>
</div>
</div>
</div>
<div id="modaldiv" class="ui modal" style="position: relative">
<i class="close icon"></i>
<div class="header"><%=results[i].title%></div>
<div class="content"><%=results[i].description%></div>
</div><!-- Should be out side of the book info div -->
<% } %>
And here is my home.js file where I post my data
$(document).ready(() => {
$(document).on("click", "#detail", function () {
$.ajax({
type: "POST",
url: '/profile',
dataType: 'text',
data: { bookName: $(this).attr("class")},
success: function (data) {
location.reload();
alert("done");
}
});
});
});
Does anyone know why this error happens and how I can solve it?
After reading your comment, I found the issue.
What you send to the server is JSON not text.
{ bookName: $(this).attr("class")} is JSON not text. Of course, value of bookName is a text, but whole data is JSON.
you should
$.ajax({
type: "POST",
url: '/profile',
contentType: 'application/json',
data: JSON.stringify({ bookName: $(this).attr("class")}),
success: function (data) {
location.reload();
alert("done");
}
});
I believe you attached bodyParser.json() to express.
Then, console.log req.body on the '/profile' router. You will see body as JSON.
EDIT: one more thing I've found is that you did't send req.body.search
It should be something like JSON.stringify({ bookName: $(this).attr("class"), search: $('.searchBook').val() }) That's why you got Error message.
EDIT2: You are trying to send form and AJAX simultaneously. It doesn't work like that. Just choose one thing. Form or AJAX. I recommend you to use AJAX. Cancel default behavior of form by using e.preventDefault() in $(document).on('click')
Look at your query param. You are passing in this line books.search(req.body.search, if you notice, req.body.searchis the query param but search is not defined in the body that you are posting: { bookName: $(this).attr("class")}, only bookname.
I believe you intend to use: books.search(req.body.bookName....
Update:
So I see you have a form that you post with search. The problem is that when that is posted, req.body.search is defined but not req.body.bookName. When then you click #detail, it is a brand new request where search is not being posted. At that point you will need to grab the value of search and post it as part of the same request.
As individual request, one contains bookName, the other search but with the code in your current state, they aren't posted together as the nodejs endpoint expects it.
Hope this is of help.
I put together a Contacts prototype MVC application that uses Knockoutjs. I'm fairly new to Knockout and was wondering if my design is correct in reaching my end goal. My end goal is basically to take an MVC Model that is passed to my Contacts view to start and achieve the following:
Mapping it to my KO Viewmodel.
Use Bootstrap Modal Popup to input my contact data.
Upon Clicking Add in Bootstrap Modal call template after posting JSON
data to controller successfully and have it display under
Edit button on each template rendered under div if clicked brings up same Modal Popup to edit that templates data.
Here's the code breakdown of what I have currently in place.
View Code
<h2>Contacts List</h2>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10"><h3>KO Results</h3></div>
</div>
<br />
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10"><div id="koResults" data-bind="template: { name: 'contactSectionTmp', foreach:Contacts }"></div></div>
</div>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10"><strong>Add</strong></div>
</div>
#*I enter data in my bootstrap modal shown below and when I click "Add" the Template below appears
in div element koResults with the data I just entered. This is the desired effect I'm looking for. *#
<div class="modal" id="contactModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" style="background-color:#B8E28D; border-color: black">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add Contact</h4>
</div>
<div class="form-horizontal">
<form id="contactModalForm" data-bind="with:newContact,submit:add">
<div class="modal-body">
<h4>Contact</h4>
<div class="form-group">
<label class="col-sm-4 control-label">Name:</label>
<div class="col-sm-8">
<input type="text" name="Name" class="form-control" data-bind="value: Name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Address:</label>
<div class="col-sm-8">
<textarea rows="4" cols="50" name="Address" class="form-control" data-bind="value: Address"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Phone:</label>
<div class="col-sm-8">
<input type="text" name="Phone" class="form-control" data-bind="value: Phone" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="formSubmitContact" class="btn btn-success">Add</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
#section scripts
<script type="text/javascript" src="~/Scripts/knockout-3.4.0.debug.js"></script>
<script type="text/javascript" src="~/Scripts/knockout.mapping-latest.debug.js"></script>
#* Knockout Template *#
<script id="contactSectionTmp" type="text/html">
<div class="row">
<div class="col-lg-3">Name:</div>
<div class="col-lg-9" data-bind="text: name"></div>
</div>
<div class="row">
<div class="col-lg-3">Address:</div>
<div class="col-lg-9" data-bind="text: address"></div>
</div>
<div class="row">
<div class="col-lg-3">Phone:</div>
<div class="col-lg-9" data-bind="text: phone"></div>
</div>
</script>
End Section
Controller Code
Pass in model to view here.
public ActionResult ContactsList()
{
ContactsVM mData = new ContactsVM();
mData.Contacts = new List<Contact>(){ new Contact { ID = 1, Name="Drew Lucacca", Address="782 Select St.", Phone="421-821-9101"},
new Contact {ID = 2, Name="Kevin Rosassa", Address = "222 Potter Lane", Phone="421-982-5222" },
new Contact {ID = 3, Name="Tim Kropp", Address = "440 PPG Place", Phone="725-434-8989"} };
return View(mData);
}
[HttpPost]
public ActionResult ContactCreate(Contact newContact)
{
var res = newContact;
ContactsVM myContacts = new ContactsVM();
myContacts.Contacts = new List<Contact>();
myContacts.Contacts.Add(new Contact { ID = 4, Name = "Santa Claus", Address = "440 Trump Plaza", Phone = "774-489-8989" });
return Json(myContacts);
}
Javascript Code
` //Main ViewModel
function ContactsVM(data) {
var self = this;
var mapping = {
'Contacts': {
create: function(options) {
return new Contact(options.data);
}
}
};
ko.mapping.fromJS(data, mapping, self);
self.newContact = ko.observable();
self.addContact = function() {
debugger;
self.newContact(new Contact({Name: '', Address: '', Phone: ''}));
}
self.add = function () {
debugger;
var jsData = data;
var jsData1 = ko.mapping.toJSON(self.newContact());
$.ajax({
url: '#Url.Action("ContactCreate", "Home")',
type: 'POST',
data: ko.mapping.toJSON(self.newContact()),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (jsonObject) {
self.contacts.push(new Contact(jsonObject));
}
});
// Close the modal.
$('#contactModal').modal('toggle');
};
self.cancel = function () {
// Close the modal.
$('#contactModal').modal('toggle');
};
//self.resetForm = function (formId) {
// var form = $('#' + formId);
// form.validate().resetForm();
// form.get(0).reset();
//};
};
function Contact(data) {
ko.mapping.fromJS(data, {}, this);
this.isEdit = ko.observable(false);
};
$(function () {
var jsonModel = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model));
var vm = new ContactsVM(jsonModel);
ko.applyBindings(vm);
});
Contact Entity
public class Contact
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
ContactsVM Entity
public class ContactsVM
{
public List<Contact> Contacts { get; set; }
}
EDIT #1
See here's the thing I know that the javascript isn't correct and note that in javascript comments asking if you can help me identify if it isn't correct how should it be.
I moved the code to new location at bottom of MVC view for the Javascript code didn't seem to find model.
Javascript - Knockout - Mapping Error
JavaScript runtime error: 'push' is undefined
self.contacts.push(new Contact(jsonObject)); < --- Error happens here.
Any help here would be greatly appreciated and I'm sure would help others as well.
I think it might be best for you to take an iterative approach at getting this working, based on the steps you have listed. Do one thing at a time, get it working, then move on to the next item. Trying to work out everything at once and test it altogether is really tough.
First Recommendation: Make your client-side models reflect your server-side models. After that, things just get easier. Since you are using ko mapping, your client-side model setup gets easier:
function ContactsVM(data) {
var mapping = {
'Contacts': {
create: function(options) {
return new Contact(options.data);
}
}
};
ko.mapping.fromJS(data, mapping, this);
this.newContact = ko.observable();
}
function Contact(data) {
ko.mapping.fromJS(data, {}, this);
this.isEdit = ko.observable(false);
}
Then you can create and apply the top-level view model fairly easily as well:
var vm = new ContactsVM(jsonModel);
ko.applyBindings(vm);
This gives you a top-level viewmodel with a fully filled Contacts observable array property. You can use the newContact property for your modal to add a new contact, just fill it with a new Contact instance.
new Contact({Name:'', Address:'', Phone:''})
When you push this new contact to the array of contacts, the DOM will automatically update to display the new contact, so you won't need to use the "ko.renderTemplate" logic that you specified. I imagine you could also show/hide the modal based on if this observable has a value if you wanted to.
Second recommendation: Try doing things with knockout first, and if you can't then use jQuery. I would not recommend using jQuery to serialize form values. Remember, you have direct access to client-side models, so you are no longer dependent upon the DOM. The ko mapping plugin has a method to unmap back to a regular JS object.
I am working on an asp.net mvc web application. on my main view i got the following create link:-
<a class="btn btn-success" data-modal="" href="/Staff/Create" id="btnCreate">
<span class="glyphicon glyphicon-plus"></span>
</a>
<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
and i have the following script:-
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
$('#myModalContent').removeData("validator");
$('#myModalContent').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#myModalContent');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('#myModalContent', dialog).submit(function () {
if ($('#myModalContent').valid()) {
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
//location.reload();
alert('www');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
}
else {
return false;
}
});
}
Now when i click on the Create link the Create action method that will return the following partial view, which will be rendered inside a modal popup :-
#model SkillManagement.Models.Staff
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Staff</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.GUID, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GUID)
#Html.ValidationMessageFor(model => model.GUID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsExternal, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IsExternal)
#Html.ValidationMessageFor(model => model.IsExternal)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
//code goes here
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
till now i have every thing working well, the Get Create action method will be called and the partial view will be rendered inside a modal popup.
but now inside my partial view if i click on "Create" button , the Post create action method will be called but not due to the javascript code . and when i check Request.IsAjax() inside my Post create action method, i got that it is not an ajax request which means the partial view send a normal Post http and not ajax request as defined inside the script,, can anyone advice what is wrong in my current approach ?
Thanks
as you can see you just pass the #myModalContent node to the bindForm function, and jQuery selector looks for
// will never find #myModalContent
$('#myModalContent', myModalContentDOMElement).submit(function () {
Instead you should do something like this
$('form', dialog).submit(function (e) {
e.preventDefault(); // stop the default form submit action
You are loading your form into the page via ajax, but the form you are loading is a regular html form if you want the form itself to use ajax, I believe are looking for #Ajax.BeginForm().
msdn documentation
#using (Ajax.BeginForm({objectparams})){
...
I would like to confirm if this limitation is by design or if I'm doing something wrong:
I have a View with two RenderPartials:
#model Heelp.ViewModels.CompanyIndexViewModel
#{ Html.RenderPartial(MVC.Company.Views.IndexSearch, Model.SearchViewModel); }
#{ Html.RenderPartial(MVC.Company.Views.IndexMap, Model.MapViewModel); }
In the first Partial View I have an Ajax.BeginForm:
#model Heelp.ViewModels.CompanyIndexSearchViewModel
#using (Ajax.BeginForm(MVC.Company.CategoryGetAllBySearch(), new AjaxOptions { UpdateTargetId = "searchCompanyResults", InsertionMode = InsertionMode.Replace }, new { #id = "searchBoxWrap" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.IsCenterFromUser)
#Html.HiddenFor(m => m.CenterLat)
#Html.HiddenFor(m => m.CenterLng)
#Html.HiddenFor(m => m.Zoom)
#Html.HiddenFor(m => m.SearchRadius)
#Html.TextBoxFor(m => m.Search, new { #placeholder = #HeelpResources.CompanyIndexViewSearchPlaceholder })
<input type="button" value="«" id="clearKeywords"/>
#Html.TextBoxFor(m => m.Location, new { #placeholder = #HeelpResources.CompanyIndexViewLocationPlaceholder })
<input type="button" value="«" id="clearLocation"/>
<input type="button" value="X" id="hereButton"/>
<input type="submit" value="#HeelpResources.CompanyIndexViewSearchButtonLabel"/>
}
<div id="searchCompanyResults" class="clearfix" style="z-index: 10; position: absolute; width: 400px;"></div>
The Ajax.BeginForm generates a PartialView in the searchCompanyResults div with a list of Ajax.ActionLink's:
#model Heelp.ViewModels.CategoryGetAllBySearchListViewModel
<p class="float-left margin-top align-left"><span>Encontrámos <em>#Model.TotalSearchCount</em> resultados nas categorias:</span></p>
<div class="clear-both">
<div id="searchResultsList" class="float-left">
<ul>
#foreach (var item in Model.CategoryGetAllBySearch)
{
<li>
#Ajax.ActionLink(
String.Format("{0} {1} ver »", item.SearchCount, item.Name),
MVC.Company.GetAllByCategory(item.Id, Model.Search, Model.Location, Model.IsCenterFromUser, Model.CenterLat, Model.CenterLng, Model.SearchRadius),
new AjaxOptions { OnBegin = "CompanyGetAllByCategoryOnBegin(" + item.Id + ")", OnSuccess = "CompanyGetAllByCategoryOnSuccess" })
</li>
}
</ul>
</div>
</div>
The problem here is that, if I don't include a link to "< script src="~/Scripts/jquery.unobtrusive-ajax.min.js" >" in the PartialView the Action.Link returns the Json text.
EDIT: One I detected is that when I click the Action.Link, the submit is made 2 times the first time, and 4 the second, and on and on growing, why?
Do I have to do this?
If you want use Ajax.BeginForm, Ajax.ActionLink and others from Ajax you should include jquery.unobtrusive-ajax.js file in your layout. It contains code that intercept click on link and submit of the form by cancel action and make it over AJAX.
You don't need include that file in partial views twice.