Update is not working in my mvc project - asp.net-mvc

hello everyone i am tring to update the database. but update is not working in my project. i used a single action to create and update.And i am using kendo grid control in this project and edit the popup template. so please check this and suggest me something why update is not working.
this is my code.
public class ImageController : Controller
{
ShoppingContext db = new ShoppingContext();
string imagename;
string path;
// GET: /Image/
public ActionResult Index()
{
return View();
}
public JsonResult GetData([DataSourceRequest] DataSourceRequest request)
{
var list = db.ImageModels.ToList();
return Json(list.ToDataSourceResult(request));
}
public ActionResult Create(IEnumerable<HttpPostedFileBase> files, ImageModel imageModel)
{
foreach (var image in files)
{
imagename = Path.GetFileName(image.FileName);
path = "~/Images/" + imagename;
var projectpath = Path.Combine(Server.MapPath("~/Images"), imagename);
image.SaveAs(projectpath);
}
var id = imageModel.Imageid;
if (id > 0)
{
imageModel.ImageName = imagename;
imageModel.ImageUrl = path;
db.SaveChanges();
}
else
{
imageModel.ImageName = imagename;
imageModel.ImageUrl = path;
db.ImageModels.Add(imageModel);
db.SaveChanges();
}
return RedirectToAction("Index");
}
}
My view
#(Html.Kendo().Grid<TelerikMVCImageProject.Models.ImageModel>()
.Name("grdImage")
.DataSource(datasource => datasource
.Ajax()
.Model(model => model.Id(p=>p.Imageid))
.Create(create => create.Action("Create", "Image"))
.Update(update => update.Action("Create", "Image"))
.Destroy(delete => delete.Action("Delete", "Image"))
.Read(read => read.Action("GetData", "Image"))
.ServerOperation(false)
.Model(model =>
{
model.Field(p => p.Imageid).Editable(true);
model.Id(p => p.Imageid);
// model.Field(p => p.isenabled).DefaultValue(true);
})
)
.Columns(columns =>
{
//columns.Bound(c => c.IMAGESIZE_ID).ClientTemplate("<input type='checkbox' value #=IMAGESIZE_ID# />").Width(50);
columns.Bound(c => c.ProductName).Width(140).Title("Product Name");
columns.Bound(c => c.ProductDesc).Title("Product Desc");
columns.Bound(c => c.ImageName).Title("Image Name");
columns.Bound(c => c.ImageUrl).Title("Image Url");
columns.Command(command =>
{
command.Edit();
command.Destroy();
//command.Custom("Edit").Action("Update", "Imagetest").Text("Edit");
});
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("ImageModel"))
.HtmlAttributes(new { style = "height: 580px;" })
.Scrollable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
)
)
My Editor Templates
#model TelerikMVCImageProject.Models.ImageModel
<style>
.k-state-default {
visibility:hidden;
}
</style>
<script>
function onSelect(e) {
alert("Select");
$demo = $("#files").val();
var filename = $demo.substr(12);
var path = "~/Images/" + filename;
$("#divimage").append('<img src = "#Url.Content("~/Images/")' + filename + '">');
alert(path);
}
function onRemove(e) {
alert("Remove");
$("#divimage").empty();
}
</script>
<form method="post" action="#Url.Action("Create")">
<table>
<tr>
#Html.HiddenFor(m=>m.Imageid)
</tr>
<tr>
<td>#Html.Label("Product Name")</td>
<td>#Html.TextBoxFor(m=>m.ProductName)</td>
</tr>
<tr>
<td>#Html.Label("Product Desc")</td>
<td>#Html.TextBoxFor(m=>m.ProductDesc)</td>
</tr>
<tr>
<td>#Html.Label("Image Desc")</td>
<td>#(Html.Kendo().Upload()
.Name("files")
.Multiple(false)
.Messages(msg => msg.Select("Browser"))
//.Async(a=>a.AutoUpload(false).Save("Save","Imagetest"))
.Events(e=>e.Select("onSelect").Remove("onRemove"))
)</td>
</tr>
<tr>
<td></td>
<td><div id="divimage" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</form>

This is because you are receiving the model from the user and not "attaching" it to the EF db context. You need to attach it before saving changes.
Try the following (in ImageController):
if (id > 0)
{
db.ImageModels.Attach(imageModel);
imageModel.ImageName = imagename;
imageModel.ImageUrl = path;
db.SaveChanges();
}

Related

Kendo Grid MVC Compilation Error when loading cshtml file

I'm getting the following error when trying to load my .cshtml file:
Compiler Error Message: CS1026: ) expected
Source Error (Line 81):
Line 79: .AutoBind(true)
Line 80:
Line 81: .DataSource(dat​asource => datasource
Line 82: .Ajax()
Line 83: .Model(model =>
I have tried refreshing the cache and removing elements from the grid but it is still not working.
cshtml page code:
#{
var guid = Guid.NewGuid();
var layoutId = guid + "page-layout";
var partialModel = new Kendo_UI_Bootstrap_Integration.ViewModels.ReportLayoutViewModel();
partialModel.Title = "Report";
partialModel.ReportHeaderData = string.Format("<span id='{0}-start-date'>Start Date:</span><br/><span id='{0}-end-date'>End Date</span>", guid);
partialModel.Id = layoutId;
}
#Html.Partial(MVC.Reports.Views.ViewNames._ReportLayout, partialModel)
<input id="GuidInput" type="hidden" value="#guid" />
<table>
<tbody>
<tr>
<td>
<span>Start Date: </span>
#(Html.Kendo().DatePicker().Name(guid + "StartDate").Footer(false))
</td>
<td style="padding-left: 10px;">
<span>End Date: </span>
#(Html.Kendo().DatePicker().Name(guid + "EndDate").Footer(false))
</td>
#if (User.IsInRole("RearingUnitRearingManager") || User.IsInRole("BackOfficeSuperUser"))
{
<td style="padding-left: 10px;">
#(Html.Kendo().DropDownListFor(m => m)
.Name("dropdown")
.DataTextField("name")
.DataValueField("nameguid")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action(MVC.ControllerName.ActionNames.Action, MVC.Controller.Name))
.ServerFiltering(true);
})
.HtmlAttributes(new { style = "width: 306px;" })
)
</td>
}
<td style="padding-left: 10px;">
#(Html.Kendo().Button().Name("Submit").Content("Submit").Events(events => events.Click("submitbutton")))
</td>
</tr>
</tbody>
</table>
<br />
#(Html.Kendo().Grid<Kendo_UI_Bootstrap_Integration.Models.DTO.dto>()
.Name("gridname")
.ToolBar(tools => { tools.Pdf(); tools.Excel(); })
.Pdf(pdf => pdf
.AllPages()
.AvoidLinks()
.Landscape()
.TemplateId(layoutId)
.PaperSize("A4")
.Scale(0.6)
.RepeatHeaders()
.Margin("7cm", "1cm", "3cm", "1cm")
.FileName("pdf.pdf")
)
.Excel(excel => excel
.AllPages(true)
.FileName("excel.xlsx"))
.EnableCustomBinding(true)
.Columns(
columns =>
{
columns.Bound(c => c.item1).Hidden();
columns.Bound(c => c.item2);
columns.Bound(c => c.item3);
columns.Bound(c => c.item4);
columns.Bound(c => c.item5);
columns.Bound(c => c.item6);
}
)
.Editable(editable => editable.Mode(GridEditMode.InCell).DisplayDeleteConfirmation(false))
.AutoBind(true)
.DataSource(dat​asource => datasource
.Ajax()
.Model(model =>
{
model.Field(m => m.item1).Editable(false);
model.Field(m => m.item2).Editable(false);
model.Field(m => m.item3).Editable(false);
model.Field(m => m.item4).Editable(false);
model.Field(m => m.item5).Editable(false);
model.Field(m => m.item6).Editable(false);
})
.Group(group => group.Add(w => w.item1))
.Read(read => read.Action(MVC.Controller.ActionNames.Actionname_Read, MVC.Controller.Name).Data("function"))
.PageSize(100)
.Batch(true)
)
.Events(ev => ev.PdfExport("ProcessPdf").ExcelExport("SetExcelFileName"))
.HtmlAttributes(new { style = "z-index: 1000; position: relative;", #class = "report-grid", report_guid = guid })
)
When I tried to double click the word 'datasource' it only highlighted half of the word, so I re-typed it and added a model.Id to the model definition and it worked.
I have no idea what happened here.

How can I get image in kendo grid pop up template in mvc?

I am trying to get image name and path in kendo grid pop up template. but not successful. I am using kendo grid pop up template.
This is my Index View:-
#(Html.Kendo().Grid<TelerikMvcAppCombo.Models.ImageModel>()
.Name("grdImageModel")
.DataSource(datasource => datasource
.Ajax()
.Model(model => model.Id(p => p.IMAGESIZE_ID))
.Create(create => create.Action("Create", "Imagetest"))
.Update(update => update.Action("Editing_Update", "Imagetest"))
.Destroy(delete => delete.Action("Delete", "Imagetest"))
.Read(read => read.Action("GetData", "Imagetest"))
.Model(model =>
{
model.Field(p => p.IMAGESIZE_ID).Editable(true);
model.Id(p => p.IMAGESIZE_ID);
model.Field(p => p.IMAGESIZE_ID).Editable(false);
// model.Field(p => p.isenabled).DefaultValue(true);
})
)
.Columns(columns =>
{
//columns.Bound(c => c.IMAGESIZE_ID).ClientTemplate("<input type='checkbox' value #=IMAGESIZE_ID# />").Width(50);
columns.Bound(c => c.IMAGESIZE_ID).ClientTemplate("<input type='checkbox' value #=IMAGESIZE_ID# />").Title("Image No");
columns.Bound(c => c.IMAGESIZE_NAME).Width(140).Title("Image Name");
columns.Bound(c => c.IMAGESIZE_DESC).ClientTemplate("<img src='" + Url.Content("~/Images/") + "#=IMAGESIZE_NAME#'/>").Title("Image");
columns.Bound(c => c.created_by).Title("Created By");
columns.Bound(c => c.created_date).Title("Created Date");
columns.Bound(c => c.modified_by).Title("Modified By");
columns.Bound(c => c.modified_date).Title("Modified Date");
columns.Command(command =>
{
command.Edit(); command.Destroy();
});
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("ImageModel"))
.HtmlAttributes(new { style = "height: 580px;" })
.Scrollable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
))
Here is my Editor template
<div>
#(Html.Kendo().Upload()
.Name("files")
.Multiple(false)
.Messages(msg => msg.Select("Browser"))
.Events(e => e
.Select("onSelect").Remove("onRemove"))
)
<div style="height:150px;width:150px;" id="divimage"></div>
</div>
Here is my controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([DataSourceRequest] DataSourceRequest request, IEnumerable<HttpPostedFileBase> files)
{
return View("");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, string imagename, string imagepath)
{
return RedirectToAction("index");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete([DataSourceRequest] DataSourceRequest request, ImageModel imagemodel)
{
return View();
}
public JsonResult GetData([DataSourceRequest] DataSourceRequest request)
{
var list = db.imageModels.ToList();
return Json(list.ToDataSourceResult(request));
}
If i used kendo upload control as a single control then i get image path and name easily but if i use kendo upload in grid popup then not get image. any suggestion.
I'm assuming your Upload control is part of a larger form. Try adding .ToClientTemplate() on the Html.Kendo().Upload()
Hopefully I understood your problem correctly.

Get Checked Rows[Selected Rows] from kendo Grid

Here is My grid, When Checkbox is Selected I want to pass the CheckBox Checked/Not Checked Value to Controller. When accessing in the controller model is not persisting the Checkbox value. Can you please guide me acheiving it.
My View :
#using(#Html.BeginForm("RequisitionApply", "Requisition", FormMethod.Post, new { approvalReason = Model, #id = "addExpenseItem" }))
{
#(Html.Kendo().Grid<ZCW.MVC.ViewModels.ManagerRequisitionSearchListViewModel>()
.Name("ManagerRequisitionApprovalGrid")
.DataSource(dataSource => dataSource
.Ajax()
.Events(e => e.RequestEnd("GetPaginationDisplay"))
.PageSize(25)
.Read(read => read.Action("GetDetails", "List").Type(HttpVerbs.Get))
//.Update(update => update.Action("Apply", "List").Type(HttpVerbs.Post))
.ServerOperation(true)
)
.Columns(columns =>
{
//RequistionName(ID)
columns.Bound(p => p.FirstName).ClientTemplate("#=FirstName#<a href='" + Url.Action("GetResource", "List", new { NameID = "#=NameID#"}) + "'>(#=NameID#) </a>").Title(#Html.LocalizedText("ID")).HtmlAttributes(new { #class = "alignleft" });
//Location
columns.Bound(p => p.Location)
.Title(#Html.LocalizedText("Location")).HtmlAttributes(new { #class = "alignleft" });
// Accept Header
columns.Template(p => p.Accept).Title("")
.HeaderTemplate("<i class='icon-ok gicn tooltips' data-original-title='Approve' data-placement='top'></i><br><div class='checker'><span><input id='selectallApprove' class='chkboxApprove' type='checkbox' onclick='ToggleChkBoxApprove(this.checked);' #= Accept ? checked='checked' : '' # /></span></div>")
.ClientTemplate("<span> <input id='checkbox' onclick='grdChkBoxClick(this); ' class='chkboxApprove' type='checkbox' name='remember' /></span>")
.HeaderHtmlAttributes(new { #class = "aligncenter" })
.HtmlAttributes(new { #class = "textaligncenter" });
//Decline Header
columns.Template(p => p.Decline).Title("")
.HeaderTemplate("<i class='icon-remove ricn tooltips' data-original-title='Decline' data-placement='top'></i><br><div class='checker'><span> <input id='selectallDecline' class='chkboxDecline' type='checkbox' onclick='ToggleChkBoxDecline(this.checked);' #= Decline ? checked='checked' : '' # /></span></div>")
.ClientTemplate("<span> <input id='checkbox1' onclick='grdChkBoxClick(this); ' class='chkboxDecline' type='checkbox' name='remember'/></span>")
.HeaderHtmlAttributes(new { #class = "aligncenter" })
.HtmlAttributes(new { #class = "textaligncenter" });
})
.AutoBind(true)
.Sortable()
.EnableCustomBinding(true)
)
<div class="pull-right">
<button type="submit" id="Apply" class="submitbtn" style="border: 0px none;"><i class="greenbtn"></i>#GlobalResourceHelper.GetGlobalResource(ResourceFiles.ButtonsResources, "BTN_APPLY")</button>
</div>
}
MyController :
public ActionResult Apply(ResourceViewModel ApprovalList)
{
// I'm not getting Checkbox Checked or not in ApprovalList
}
You have to do this.
columns.Bound(x => x.IsChecked).ClientTemplate(
"<input name='IsChecked' class='chkBox' type='checkbox'
data-bind='checked: IsChecked' #= IsChecked ? checked='checked' : '' #/>");
//check document ready
var grid = $("#Grid").data("kendoGrid");
grid.tbody.on("change", ".chkBox", function (e) {
var row = $(e.target).closest("tr");
var item = grid.dataItem(row);
//item.set("IsChecked", $(e.target).is(":checked") ? 1 : 0);
kendo.bind(this,item);//this line or above line will handle this
});
Post the Grid using an ajax call and send the Grid's data.
var gridData = $("#Grid").data("kendoGrid");
//AJAX etc...
data: JSON.stringify(gridData.dataSource.view()),

Multiple Kendo Grids in a Razor View

I'm looping through my Model in a Razor View and wanted to display multiple Kendo Grids. However I'm getting all empty grids even though the Item_Read is being executed when the loop happens.
Any ideas?
Source:
#foreach (var itemM in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => itemM.id)
</td>
<td>
#(Html.Kendo().Grid<SomeOtherModel>()
.Name("KendoGrid" + itemM.id)
.Columns(columns =>
{
columns.Bound(p => p.title);
columns.Bound(p => p.details);
})
.AutoBind(true)
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.itemId);
model.Field(p => p.itemId).Editable(false);
})
.Read(read => read.Action("Item_Read", "Controller", new { id = itemM.id }))
)
)
</td>
</tr>
}
The problem was my ViewModel, one of the properties was null.

Post the Kendo Grid Data on Form Submit

I want to Post the data from a Kendo Grid to the server, and save it to a database.
For this I have used form like so:
#using (Html.BeginForm("MainDocumentSave","Document"))
{
<div class="row-fluid">
<div class="span10">
#(Html.Kendo().Grid<Invoice.Models.ViewModels.SegmentViewModel>()
.Name("Segment")
.TableHtmlAttributes(new { style = "height:20px; " })
.Columns(columns =>
{
columns.Bound(p => p.AirlineShortName).EditorTemplateName("AirlineEditor").Title("Airline").ClientTemplate("#=AirlineName#").Width(5);
columns.Bound(p => p.DepartureDate).Width(9);
columns.Bound(p => p.Arrives).EditorTemplateName("ArrivalLocation").Title("Arrival").ClientTemplate("#=Arrives#").Width(5);
columns.Bound(p => p.ArrivalDate).Width(7);
columns.Bound(p => p.FlightNumber).Width(8);
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Navigatable()
.Sortable()
.Scrollable(scr => scr.Height(200))
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.AirlineName))
.Create("Editing_Create", "Grid")
.Read("Segment_Read", "Document")
.Update("Editing_Update", "Grid")
.Destroy("Editing_Destroy", "Grid")
)
)
</div>
</div>
<button type="submit" class="btn btn-primary"> Save Segments</button>
}
But after submitting, the data inside the Kendo Grid is not Posted. How can I Post Kendo Grid Data to the Server?
The Grid is not a form element and it cannot be simply posted to the server. You can take advantage of the templates that the Grid provide and create hidden elements based on the different row models which to be submitted to the server.
The same approach is used in this code library which demonstrates exactly what you are searching for.
The grid data isn't in form elements. The form elements appear only when a cell is being edited, then it is removed. You can't post the data to the server by using a form submit button.
The proper way to to this would be by adding the 'save' command button that the grid provides itself:
#(Html.Kendo().Grid<Invoice.Models.ViewModels.SegmentViewModel>()
.Name("Segment")
.ToolBar(toolbar => {
toolbar.Save(); // add save button to grid toolbar
})
// ... rest of options ...
Or by calling saveChanges() on the Grid widget:
<button type="button" id="save">Save Segments</button>
$("#save").on("click", function () {
$("#Segment").data("kendoGrid").saveChanges();
});
Suppose I have three kendo grids and two textboxs in my page. Now I want to post all data along with data of three grid. I did this by below style.
#model DAL.ViewModel.ProfileViewModel
#{
ViewBag.Title = "Profile";
Layout = "~/Views/Shared/_LayoutAfterLogin.cshtml";
}
<h2>Profile</h2>
<div>
<h4>ApplicationUser</h4>
<hr />
<dl class="dl-horizontal"></dl>
<form id="frmProfile">
<div>
<label>Email<span class="mandatory"></span></label>
#Html.Kendo().TextBoxFor(model => model.Email)
</div>
<div>
<label>UserName<span class="mandatory"></span></label>
#Html.Kendo().TextBoxFor(model => model.UserName)
</div>
</form>
#(Html.Kendo().Grid<DAL.ViewModel.PhoneViewModel>()
.Name("PhoneGrid")
.Columns(columns =>
{
columns.Bound(p => p.PhoneID).Groupable(false);
columns.Bound(p => p.PhoneType).Width(160);
columns.Bound(p => p.PhoneNumber).Width(120);
columns.Bound(p => p.IsPrimary).Width(120);
columns.Command(command => command.Destroy()).Width(90);
})
.ToolBar(toolBar =>
{
toolBar.Create();
// toolBar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Sortable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.PhoneID);
model.Field(p => p.PhoneID).Editable(false);
})
.PageSize(20)
.Read(read => read.Action("PhoneList", "Account"))
.Create(create => create.Action("AddPhone", "Account"))
.Update(update => update.Action("EditPhone", "Account"))
.Destroy(destroy => destroy.Action("DeletePhone", "Account"))
)
)
</div>
<p>
<button type="button" id="btnSave">Save</button>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
#Html.ActionLink("Back to List", "Index")
</p>
//jquery
$("#btnSave").on("click", function () {
sendData();
});
function sendData() {
var grid = $("#PhoneGrid").data("kendoGrid"),
parameterMap = grid.dataSource.transport.parameterMap;
//get the new and the updated records
var currentData = grid.dataSource.data();
var updatedRecords = [];
var newRecords = [];
for (var i = 0; i < currentData.length; i++) {
if (currentData[i].isNew()) {
//this record is new
newRecords.push(currentData[i].toJSON());
} else if (currentData[i].dirty) {
updatedRecords.push(currentData[i].toJSON());
}
}
//this records are deleted
var deletedRecords = [];
for (var i = 0; i < grid.dataSource._destroyed.length; i++) {
deletedRecords.push(grid.dataSource._destroyed[i].toJSON());
}
var serializedData = $("#frmProfile").serializeObject();
var data = {};
$.extend(data, parameterMap({ updated: updatedRecords }), parameterMap({ deleted: deletedRecords }), parameterMap({ new: newRecords }));
var finaldata = {};
$.extend(finaldata, parameterMap({ phone: data }), parameterMap({ email: data }), parameterMap({ address: data }), parameterMap({ pagedata: serializedData }));
$.ajax({
url: '#Url.Action("UpdateCreateDelete1", "Account")',
data: JSON.stringify(finaldata),
type: "POST",
contentType: 'application/json',
dataType: 'json',
error: function (e) {
alert('error');
//Handle the server errors using the approach from the previous example
},
success: function () {
grid.dataSource._destroyed = [];
//refresh the grid - optional
// grid.dataSource.read();
}
})
}
jQuery.fn.serializeObject = function () {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function () {
var value;
if (this.value != null) {
value = this.value;
} else {
value = '';
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
};
//action method
public ActionResult UpdateCreateDelete1(
[Bind(Prefix = "phone.updated")]List<PhoneViewModel> updatedPhone,
[Bind(Prefix = "phone.new")]List<PhoneViewModel> newPhone,
[Bind(Prefix = "phone.deleted")]List<PhoneViewModel> deletedPhone,
[Bind(Prefix = "email")]List<PhoneViewModel> emaillist,
[Bind(Prefix = "address")]List<PhoneViewModel> addresslist,
[Bind(Prefix = "pagedata")] ProfileViewModel pagedata
)
{
}

Resources