Get selected column information in Kendo UI grid - asp.net-mvc

I have one requirement for asp.net MVC application and for that inside Kendo UI grid, I have customized one column with combo box and two buttons for performing adding or deletion of any user selected value or manual typed value from combo box control.
But I am not able to get how I can get button click information for any specific row of that column.
Kindly guide how I can achieve such kind of behavior.
Sample Code for Grid is below and I want to get clickable for Category Column.
#(Html.Kendo().Grid<GridHeaderTemplate.Models.ProductModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.ProductName);
columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "CategoryID", "CategoryName")
.Title("Category").HtmlAttributes(new
{
#class = "templateCell"
}).ClientTemplate("<table cellspacing='0' class='data-row data-personal'><tr>" +
"<td>#=data.Category.CategoryName# <span class='custom-arrow k-icon k-i-arrow-s'></span></td>" +
"<td><button id='customButton'>Add</button> <span></span> <button id='customButton1'>Delete</button></td>" +
"</tr></table>")
.HeaderTemplate(
#<text>
<table cellspacing="0" class="data-header">
<tr>
<td colspan="2"><strong>Category</strong></td>
</tr>
<tr>
<td>Category Name</td>
<td>Settings</td>
</tr>
</table>
</text>
)
.Width(300);//.ClientTemplate("#=data.Category.CategoryName# <span class='custom-arrow k-icon k-i-arrow-s'></span>"); ;
columns.Bound(p => p.UnitPrice).Width(150);
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolBar =>
{
toolBar.Save();
toolBar.Create();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable()
.Groupable()
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.ProductID);
model.Field(p => p.ProductID).Editable(false);
model.Field(p => p.CategoryID).DefaultValue(1);
})

Enter some code to help us helping you..
You need to have in your object the Id that you want to add or delete,
If you created a client template adding the two specific buttons and calling a javascript function, then you have acess to the properties of the row
for instance:
column.Bound(c=>c.Id).hidden(true);
column.Bound(c=>c.Name).ClientTemplate("<span onclick='AddToThisId(#=Id#)'>add</span>");
Edited:
CONTROLLER:
public ActionResult Delete(int id)
{
try
{
//Delete....
}
catch (Exception ex)
{
result.SetInsucess("Erro a apagar registo: " + ex.Message + ".");
}
return Json(true, JsonRequestBehavior.AllowGet);
}
VIEW
<script>
function AddSomethingBaseOnId(id){
$.ajax({
cache: false,
type: 'GET',
data: { Id: Id },
contentType: "application/json",
url: "Controller/AddAction",
success: function (data) {
alert("sucess");
},
fail: function (jqXHR, textStatus) {
alert("Ocorreu um erro: " + textStatus);
$("#" + uid).hide();
}
});
}
function DeleteSomethingBaseOnId(id){
$.ajax({
cache: false,
type: 'GET',
data: { Id: Id },
contentType: "application/json",
url: "Controller/DeleteAction",
success: function (data) {
alert("sucess");
},
fail: function (jqXHR, textStatus) {
alert("Ocorreu um erro: " + textStatus);
$("#" + uid).hide();
}
});
}
</script>
in your client template:
"<td>#=data.Category.CategoryName# <span class='custom-arrow k-icon k-i-arrow-s'></span></td>" +
"<td><button id='customButton' onclick="AddSomethingBaseOnId(#=data.Id#)">Add</button> <span></span> <button id='customButton1' onclick="DeleteSomethingBaseOnId(#=data.Id#)">Delete</button></td>" +

Related

Insert Multiple rows in Kendo Grid on load without for loop

I need to Display 100 empty rows in Kendo grid on load as shown here Image without using for loop.
I have tried this:-
$(document).ready(function () {
var grid = $("#AlertRowGrid").data("kendoGrid");
var datasource = grid.dataSource;
for (i = 0; i < 100; i++) {
datasource.add({ PhoneNumber: '', Field1: '', Field2: '', Field3: '', Field4: '', Field5: '', Field6: '', Field7: '', Field8: '', Field9: '', Field10: '' });
}
});
But using for loop consumes much loading time.So is there any better option other than for loop to display multiple rows in kendo grid?
My grid is as below:-
#(Html.Kendo().Grid<SCC.Business.Models.Point_of_Service.Custom.SendAlertsDataModel>()
.Name("AlertRowGrid")
.Columns(columns =>
{
columns.Bound(c => c.PhoneNumber).ClientTemplate("<input type='text' value='#:PhoneNumber#' id='Phone' maxlength='12' onchange = EditGridRow(this) placeholder = '000-000-0000' class='MaskPhone'/>").Title(General.PhoneNumber).Width("10%").HtmlAttributes(new { #class = "PhoneNumber" });
columns.Bound(c => c.Field1).ClientTemplate("<input type='text' value='#:Field1#' id='Field1' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field1).Width("10%").HtmlAttributes(new { #class = "Field1" });
columns.Bound(c => c.Field2).ClientTemplate("<input type='text' value='#:Field2#' id='Field2' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field2).Width("10%").HtmlAttributes(new { #class = "Field2" });
columns.Bound(c => c.Field3).ClientTemplate("<input type='text' value='#:Field3#' id='Field3' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field3).Width("10%").HtmlAttributes(new { #class = "Field3" });
columns.Bound(c => c.Field4).ClientTemplate("<input type='text' value='#:Field4#' id='Field4' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field4).Width("10%").HtmlAttributes(new { #class = "Field4" });
columns.Bound(c => c.Field5).ClientTemplate("<input type='text' value='#:Field5#' id='Field5' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field5).Width("10%").HtmlAttributes(new { #class = "Field5" });
columns.Bound(c => c.Field6).ClientTemplate("<input type='text' value='#:Field4#' id='Field4' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field6).Width("10%").HtmlAttributes(new { #class = "Field6" });
columns.Bound(c => c.Field7).ClientTemplate("<input type='text' value='#:Field7#' id='Field7' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field4).Width("10%").HtmlAttributes(new { #class = "Field7" });
columns.Bound(c => c.Field8).ClientTemplate("<input type='text' value='#:Field8#' id='Field8' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field8).Width("10%").HtmlAttributes(new { #class = "Field8" });
columns.Bound(c => c.Field4).ClientTemplate("<input type='text' value='#:Field9#' id='Field9' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field9).Width("10%").HtmlAttributes(new { #class = "Field9" });
columns.Bound(c => c.Field10).ClientTemplate("<input type='text' value='#:Field10#' id='Field10' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field4).Width("10%").HtmlAttributes(new { #class = "Field10" });
}).Scrollable(x => x.Height(400)).Events(e => e.DataBound("onDataBound"))
)
Your help will be appreciated Thanks.
Every time you update the grid's data source, it gets refreshed. I've changed your code to build the data source first and assign it to the grid afterwards:
$(document).ready(function () {
console.log("S: " + new Date());
var data = [];
for (var i = 0; i < 100; i++) {
data.push({ PhoneNumber: '', Field1: '', Field2: '', Field3: '', Field4: '', Field5: '', Field6: '', Field7: '', Field8: '', Field9: '', Field10: '' });
}
var dataSource = new kendo.data.DataSource({
data: data
});
var grid = $("#AlertRowGrid").getKendoGrid();
grid.setDataSource(dataSource);
grid.dataSource.read();
console.log("E: " + new Date());
});
According to https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setdatasource it should not be necessary to reload the data source manually. But it did not work without.
Your code took 5 seconds on my machine. Now it is less than a second.

Cannot export hidden columns in Kendo Grid

I want to hide some columns on Kendo Grid and export them to the excel as the visible columns. However, using Hidden(true) or Visible(false) does not make any sense and these fields are not exported. The workarounds on this page is not working. Any idea?
View:
#(Html.Kendo().Grid<ContactViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(m => m.NameSurname).Title("Name Surname").Width("%100");
columns.Bound(m => m.InstituteName).Title("Institute Name").Width("250px");
columns.Bound(m => m.CityName).Title("City").Width("145px");
columns.Bound(m => m.RegionName).Title("Region").Width("145px");
columns.Bound(m => m.ContactMobile).Title("Mobile").Width("125px");
columns.Bound(m => m.ContactAddress).Title("Address").Hidden(true); //I want to export these fields
columns.Bound(m => m.ContactAddress).Title("Address").Visible(false); //I want to export these fields
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<button class="btn btn-primary btn-xs pull-right k-button k-button-icontext k-grid-excel">
<span class="k-icon k-excel"></span>
Liste (xls)
</button>
</div>
</text>);
})
.Excel(excel => excel
.FileName("List.xlsx")
.Filterable(true)
.AllPages(true)
.ProxyURL(Url.Action("Excel_Export_Save", "Controller"))
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Index_Read", "Controller"))
.ServerOperation(false)
.PageSize(12)
)
)
)
See this solution Plunker, suggested solution on Telerik website.
To show column in your export functionality, bind this 'excelExport' event of that grid.
var exportFlag = false;
$("#grid").data("kendoGrid").bind("excelExport", function (e) {
if (!exportFlag) {
// e.sender.showColumn(0); for demo
// for your case show column that you want to see in export file
e.sender.showColumn(5);
e.sender.showColumn(6);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn(5);
e.sender.hideColumn(6);
exportFlag = false;
}
});
Demo: Hide First column and show in export file
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/grid/excel-export">
<style>
html {
font-size: 12px;
font-family: Arial, Helvetica, sans-serif;
}
</style>
<title></title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.material.min.css" />
<script src="http://cdn.kendostatic.com/2015.1.318/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.318/js/jszip.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.318/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="grid" style="width: 900px"></div>
<script>
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "Kendo UI Grid Export.xlsx",
proxyURL: "http://demos.telerik.com/kendo-ui/service/export",
filterable: true
},
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
},
schema: {
model: {
fields: {
UnitsInStock: {
type: "number"
},
ProductName: {
type: "string"
},
UnitPrice: {
type: "number"
},
UnitsOnOrder: {
type: "number"
},
UnitsInStock: {
type: "number"
}
}
}
},
pageSize: 7
},
sortable: true,
pageable: true,
columns: [{
width: "10%",
field: "ProductName",
title: "Product Name",
hidden: true
}, {
width: "10%",
field: "UnitPrice",
title: "Unit Price"
}, {
width: "10%",
field: "UnitsOnOrder",
title: "Units On Order"
}, {
width: "10%",
field: "UnitsInStock",
title: "Units In Stock"
}]
});
var exportFlag = false;
$("#grid").data("kendoGrid").bind("excelExport", function (e) {
if (!exportFlag) {
e.sender.showColumn(0);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn(0);
exportFlag = false;
}
});
</script>
</div>
</body>
</html>
I try with this example also, it is same as my previous answer just jQuery binding event will be different.
You just need to do changes in code by adding grid event Events(x => x.ExcelExport("excelExport")) and jQuery function excelExport(e) {}.
Also use only Hidden(true) to hide grid column.
ViewModel is something like this :
public class ContactViewModel
{
public string NameSurname { get; set; }
public string InstituteName { get; set; }
public string CityName { get; set; }
public string RegionName { get; set; }
public string ContactMobile { get; set; }
public string ContactAddress { get; set; }
}
Controller will be:
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Index_Read([DataSourceRequest]DataSourceRequest request)
{
var listOfContactViewModel = new List<ContactViewModel>() {
new ContactViewModel(){ NameSurname = "N1", InstituteName = "I1", CityName ="C1",RegionName = "R1",ContactMobile = "M1", ContactAddress = "C1" },
new ContactViewModel(){ NameSurname = "N2", InstituteName = "I2", CityName ="C2",RegionName = "R2",ContactMobile = "M2", ContactAddress = "C2" },
new ContactViewModel(){ NameSurname = "N3", InstituteName = "I3", CityName ="C3",RegionName = "R3",ContactMobile = "M3", ContactAddress = "C3" },
new ContactViewModel(){ NameSurname = "N4", InstituteName = "I4", CityName ="C4",RegionName = "R4",ContactMobile = "M4", ContactAddress = "C4" },
new ContactViewModel(){ NameSurname = "N5", InstituteName = "I5", CityName ="C5",RegionName = "R5",ContactMobile = "M5", ContactAddress = "C5" }
};
return Json(listOfContactViewModel.ToDataSourceResult(request),JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Excel_Export_Save(string contentType, string base64, string fileName)
{
var fileContents = Convert.FromBase64String(base64);
return File(fileContents, contentType, fileName);
}
}
And View for this:
<h2>Index</h2>
#(Html.Kendo().Grid<KendoUIMVC5.Models.ContactViewModel>()
.Name("Grid")
.Events(x => x.ExcelExport("excelExport"))
.Columns(columns =>
{
columns.Bound(m => m.NameSurname).Title("Name Surname").Width("%100");
columns.Bound(m => m.InstituteName).Title("Institute Name").Width("250px");
columns.Bound(m => m.CityName).Title("City").Width("145px");
columns.Bound(m => m.RegionName).Title("Region").Width("145px");
columns.Bound(m => m.ContactMobile).Title("Mobile").Width("125px");
columns.Bound(m => m.ContactAddress).Title("Address").Hidden(true); //I want to export these fields
columns.Bound(m => m.ContactAddress).Title("Address").Hidden(false); //I want to export these fields
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<button class="btn btn-primary btn-xs pull-right k-button k-button-icontext k-grid-excel">
<span class="k-icon k-excel"></span>
Liste (xls)
</button>
</div>
</text>);
})
.Excel(excel => excel
.FileName("List.xlsx")
.Filterable(true)
.AllPages(true)
.ProxyURL(Url.Action("Excel_Export_Save", "Test"))
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Index_Read", "Test"))
.ServerOperation(false)
.PageSize(12)
)
)
<script type="text/javascript">
var exportFlag = false;
function excelExport(e)
{
if (!exportFlag) {
e.sender.showColumn(5);
e.sender.showColumn(6);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn(5);
e.sender.hideColumn(6);
exportFlag = false;
}
}
</script>
...
columns.Bound(x => x.Id).Visible(false);
columns.Bound(x => x.Siege).Width(150);
columns.Bound(x => x.Societe).Width(150);
columns.Bound(x => x.Matricule).Width(100).Hidden(true);
columns.Bound(x => x.Civilite).Width(80);
...
var exportFlag = false;
$("#myGrid").data("kendoGrid").bind("excelExport", function (e) {
var grid = e.sender;
var columns = grid.columns;
if (!exportFlag) {
$.each(columns, function (index, value) {
var col = this;
if (col.hidden == true) {
col.hidden = false;
}
});
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
}
else {
$.each(columns, function (index, value) {
var col = this;
if (col.hidden == false) {
col.hidden = true;
}
});
exportFlag = false;
}
});

Kendo grid removes tick mark?

I have below kendo grid. I want remove 'Tick mark' and 'Done' after asyn upload.
How to do that? Following code removes the text 'Done' but tick mark is still visible.
Kendo upload control:
#(Html.Kendo().Upload()
.Name("files")
.Messages( m => m.Select("Browse"))
.Async(a => a
.Save("SaveAttachment", "Document")
.Remove("Remove", "Document")
.AutoUpload(true)
)
.Events(events => events
.Success("onSuccess")
)
.Multiple(false)
)
$("#files").kendoUpload({
multiple: true,
async: {
saveUrl: "...",
removeUrl: "...",
autoUpload: false
},
localization: {
// Override built-in text "Done"
headerStatusUploaded:"",
statusUploaded:""
}
...
});
To hide all messages ('Uploading...' and 'Done') and icons you can use simple css:
.k-upload .k-upload-status.k-upload-status-total {
display: none;
}
If you want to hide just 'Done' and tick icon as you said - you can do it by using javascript events:
#(Html.Kendo().Upload()
.Name("files")
.Messages(m => m.Select("Browse"))
.Async(a => a
.Save("Submit", "Watchdog")
.AutoUpload(true)
)
.Events(events => events
.Success("onSuccess")
.Select("onSelect")
.Complete("onComplete")
)
.Multiple(false)
)
<script>
function onSelect(e) {
e.sender.element.closest('.k-upload').find('.k-upload-status.k-upload-status-total').show();
}
function onComplete(e) {
e.sender.element.closest('.k-upload').find('.k-upload-status.k-upload-status-total').hide();
}
</script>

Kendo UI Grid in a Splitter

I've got a splitter in my layout, to display informations.
My display is good, but when I had my grid in my index.html (which is called in my layout by #RenderBody() ) , my splitter isn't well displayed anymore ...
Everything is on a single page, without splitter ...
Any ideas ?
EDIT :
Yes sorry .
There's my Controller :
public class HomeController : Controller
{
private static string path = #"C:\LogIngesup\log.xml";
public ActionResult Index()
{
DataTable logs = Write_Log.Read.loadXML(path);
return View(logs);
}
}
There my layout :
<body>
#(Html.Kendo().Splitter()
.Name("vertical")
.Orientation(SplitterOrientation.Vertical)
.Panes(verticalPanes =>
{
verticalPanes.Add()
.HtmlAttributes(new { id = "middle-pane" })
.Scrollable(false)
.Collapsible(false)
.Content(
Html.Kendo().Splitter()
.Name("horizontal")
.HtmlAttributes(new { style = "height: 100%;" })
.Panes(horizontalPanes =>
{
horizontalPanes.Add()
.HtmlAttributes(new { id = "left-pane" })
.Size("230px")
.Resizable(false)
.Collapsible(true)
.Content(#<div>#RenderPage("~/Views/Home/Calendrier.cshtml")</div>);
horizontalPanes.Add()
.HtmlAttributes(new { id = "center-pane" })
.Content(#<div class="pane-content">
<section id="main">
#RenderBody()
</section>
</div>);
horizontalPanes.Add()
.HtmlAttributes(new { id = "right-pane" })
.Collapsible(true)
.Size("220px")
.Content(#<div class="pane-content">
#RenderPage("~/Views/Home/XML.cshtml")
</div>);
}).ToHtmlString()
);
verticalPanes.Add()
.Size("70px")
.HtmlAttributes(new { id = "bottom-pane" })
.Resizable(false)
.Collapsible(true)
.Content(#<div class="pane-content" style="text-align:center">
<p>Application développée par : Dan</p>
</div>);
}))
</body>
And eventually my index.html :
#{
ViewBag.Title = "LogApp";
}
#model System.Data.DataTable
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns => {
foreach (System.Data.DataColumn column in Model.Columns)
{
columns.Bound(column.DataType, column.ColumnName);
}
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
)
I'm aware about any suggestion on my code :)
Furthermore I've got an issue :
When I try to add this in my grid (index.html):
.DataSource(datasource=>datasource
.Ajax()
.PageSize(10)
)
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
I can't go to other page, and can't select a row ... Can you help me ?
(It works when I write directly the url : localhost\?Grid-page=2)
I had the same problem when putting a Kendo UI Splitter inside a Kendo UI Tabcontrol.
When the Tabcontrol was made before the Splitter it was making this problem, but when I just reversed the order it worked fine.
i.e I changed from:
$(document).ready(function ()
{
$("#ManagementMenu").kendoTabStrip();
$("#splitter").kendoSplitter({
panes: [
{ size: "200px", resizable: false},
{ size: "500px", collapsible: false}
],
});
}
to
$(document).ready(function ()
{
$("#splitter").kendoSplitter({
panes: [
{ size: "200px", resizable: false},
{ size: "500px", collapsible: false}
],
});
$("#ManagementMenu").kendoTabStrip();
}
and the problem was fixed.

ASP.NET MVC 3 + jQuery Ajax JSON - Prevent JSON from opening in new page

I have an Action Method that returns a JSON-serialized object. The problem I'm having is that the JSON returned is opening in a new page, instead of being processed by the "success" function of the jquery.Ajax method.
Here's the controller action:
[HttpPost]
public ActionResult AddAssignment(AssignmentViewModel avm)
{
db.Assignments.Add(new Assignment
{
Name = avm.Name,
DueDate = DateTime.Parse(avm.DueDate),
CourseID = avm.CourseID,
IsComplete = false
});
db.SaveChanges();
avm.Course = db.Courses
.Where(x => x.CourseID == avm.CourseID)
.SingleOrDefault()
.Name;
return Json(avm);
}
Here's the View (form):
#model Fooburg.Mvc.Models.AssignmentViewModel
<h2 style="margin: 0 0 24px 0">Add Assignment:</h2>
#using (Html.BeginForm("AddAssignment",
"Assignments",
FormMethod.Post,
new { #id = "add-assignment-form" }))
{
<dl class="tabular">
<dt>Course:</dt>
<dd>
#Html.DropDownListFor(x => x.CourseID, new SelectList(ViewBag.Courses, "CourseID", "Name"))
</dd>
<dt>Assignment:</dt>
<dd>
#Html.TextBoxFor(x => x.Name)
</dd>
<dt>Due Date:</dt>
<dd>
#Html.TextBoxFor(x => x.DueDate, new { #class = "date" })
<script type="text/javascript">
$(function () {
$('.date').datepicker({ dateFormat: "mm/dd/yy" });
});
</script>
</dd>
</dl>
<p>
<input type="submit" value="Add Assignment" id="new-assignment-submit" />
</p>
}
And here's the javascript:
$(function () {
$('#add-assignment-form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
});
});
I have tried the event.stopPropogation() method, but didn't change my problem
EDIT: I've updated my javascript to the following, but I'm still getting the same result
$('#add-assignment-form').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
You need to return false; or event.preventDefault() to prevent the browser from submitting the form normally.
You have two options here,
Use Ajax.BeginForm() instead of Html.BeginForm() that you would use like
#using(Ajax.BeginForm( "AddAssignment", "Assignments",
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "output"})) {
...
}
and get rid of the javascript code.
Or call event.prevendDefault() in
$('#add-assignment-form').submit(function (event) {
// ...
event.preventDefault();
});
Just specify
return false;
after your $.ajax() call
UPDATE
$(function () {
$('#add-assignment-form input[type=submit]').click(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
});
Have you checked if there are other javascript errors on the page that might be causing this unexpected behaviour? I would suggest Firebug for FF or Javascript Console for Chrome.
Also, I've noticed that sometime FF has issues if you don't specify the script type, so make sure your type is set to "text/javascript".
hth,
-covo

Resources