Set JsonRequestBehavior to AllowGet only happens on combo and dropdown boxes? - kendo-ui

I have a MVC4 .net app using Kendo UI. I get the set jsonrequestbehavior issue for comboboxes and dropdowns but not listview when they all use the same function to read. I want to populate a dropdown box. Am I missing something?
Relevant Code:
relevant part of the cshtml(view):
<script type="text/x-kendo-tmpl" id="propertiestemplate">
<div class="partnersss">
<h5>#:PartnerID#</h5>
<p>#:PartnerName#</p>
</div>
</script>
<div class="editor-field">
#(Html.Kendo().DropDownList()
.Name("partnerddl")
.HtmlAttributes(new { style = "width: 250px" })
.DataTextField("PartnerName")
.DataValueField("PartnerID")
.AutoBind(true)
.DataSource(source => {
source.Read(read =>
{
read.Action("GetPropertyPartners", "Property", new { onlyActive = true });
});
})
)
#(Html.Kendo().ComboBox()
.Name("partnercb")
.Placeholder("Select Partner...")
.DataTextField("PartnerName")
.DataValueField("PartnerID")
.AutoBind(true)
.Filter("contains")
.MinLength(3)
.DataSource(source => {
source.Read(read =>
{
read.Action("GetPropertyPartners", "Property", new { onlyActive = true });
}).ServerFiltering(true);
})
)
#(Html.Kendo().ListView<MyVegas.Rewards.Nucleus.Entities.PropertyPartnerView>()
.Name("partnerlv")
.TagName("div")
.ClientTemplateId("propertiestemplate")
.DataSource(ds => ds
.Read(read => read.Action("GetPropertyPartners", "Property", new { onlyActive = true }))
)
)
#Html.ValidationMessageFor(model => model.PartnerID)
</div>
controller:
public JsonResult GetPropertyPartners([DataSourceRequest] DataSourceRequest dsRequest, bool onlyActive)
{
partners = property.GetPartnersForProperties(onlyActive);
var result = partners.ToDataSourceResult(dsRequest);
return Json(result);
}
Result Protocol Host URL Body Caching Content-Type Process
27 500 HTTP localhost:2590 /Property/GetPropertyPartners?onlyActive=True 8,783 private text/html; charset=utf-8 iexplore:17452
28 500 HTTP localhost:2590 /Property/GetPropertyPartners?onlyActive=True 8,783 private text/html; charset=utf-8 iexplore:17452
29 200 HTTP localhost:2590 /Property/GetPropertyPartners?onlyActive=True 132 private application/json; charset=utf-8 iexplore:17452
number 27 and 28 give this json back(incorrect):
<!DOCTYPE html>
<html>
<head>
<title>This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.]
System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +362369
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9628700
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</pre></code>
</td>
</tr>
</table>
<br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044
</font>
</body>
</html>
<!--
[InvalidOperationException]: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
at System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.<BeginInvokeAction>b__20()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
number 29 gives this json back(correct):
{"Data":[{"PartnerID":1,"PartnerName":"test1"},{"PartnerID":2,"PartnerName":"test2"}],"Total":2,"AggregateResults":null,"Errors":null}

Reposting Tom Maxwell's comment as answer.
Changed:
public JsonResult GetPropertyPartners([DataSourceRequest] DataSourceRequest dsRequest, bool onlyActive)
{
partners = property.GetPartnersForProperties(onlyActive);
var result = partners.ToDataSourceResult(dsRequest);
return Json(result);
}
to:
public JsonResult GetPropertyPartners([DataSourceRequest] DataSourceRequest dsRequest, bool onlyActive)
{
partners = property.GetPartnersForProperties(onlyActive);
return Json(partners, JsonRequestBehavior.AllowGet);
}

Related

How to upload,display,download and delete files using spring mvc

Hi am trying to do operations like uploading a file,displaying a file,downloading a file and deleting a file using spring mvc i got success in uploading file and deleting file all operations working fine but then whats happening is when i do uploading the uploaded file or image displaying or downloading twice and getting
java.lang.IllegalStateException: getOutputStream() has already been called for this response
<form method="post" action="doUpload" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Pick file #1:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td>Pick file #2:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
<table border="1" bgcolor="black" width="600px">
<tr style="background-color: teal; color: white; text-align: center;"
height="40px">
<td>File Name</td>
<td>Image</td>
<td>Download</td>
<td>Delete</td>
</tr>
<c:forEach items="${employeeList}" var="user">
<tr style="background-color: white; color: black; text-align: center;"
height="30px">
<td><c:out value="${user.fileName}" /></td>
<td><img src="show?id=${user.id}" /></td>
<td>Download</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
#Controller
#RequestMapping("/")
public class RegistrationController {
#Autowired
private IRegistrationService registerService;
#RequestMapping(value = "/saveParentAndStudentFromAdmin", method = RequestMethod.POST)
public ModelAndView saveParentAndStudentByAdmin(
#ModelAttribute Student student,
#RequestParam CommonsMultipartFile[] fileUpload) {
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload) {
System.out.println("Saving file: "
+ aFile.getOriginalFilename());
student.setFileName(aFile.getOriginalFilename());
student.setFileType(aFile.getContentType());
student.setData(aFile.getBytes());
registerService.saveParentAndStudentByAdmin(student);
}
}
java.util.List<Student> uploadedFiles = registerService.findAllFiles();
return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
uploadedFiles);
}
#RequestMapping("delete")
public ModelAndView deleteUser(#RequestParam int id) {
registerService.deleteRow(id);
java.util.List<Student> uploadedFiles = registerService.findAllFiles();
return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
uploadedFiles);
}
#RequestMapping("show")
public ModelAndView displayImage(#RequestParam int id,
HttpServletResponse response, HttpServletRequest request) {
System.out.println("Id to display image: " + id);
Student item = registerService.get(id);
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
try {
response.getOutputStream().write(item.getData());
} catch (IOException e) {
e.printStackTrace();
}
try {
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView("StudentEnrollmentFromAdmin");
}
#RequestMapping("downalod")
public ModelAndView downloadFile(#RequestParam int id,
HttpServletResponse response, HttpServletRequest request) {
System.out.println("Id to download: " + id);
Student student = registerService.get(id);
response.setContentType(student.getFileType());
response.setContentLength(student.getData().length);
response.setHeader("Content-Disposition", "attachment; filename=\""
+ student.getFileName() + "\"");
try {
FileCopyUtils.copy(student.getData(), response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
java.util.List<Student> uploadedFiles = registerService.findAllFiles();
return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
uploadedFiles);
}
}
If I correctly understood your question you may do something like this:
public ResponseEntity<InputStreamResource> getFile(#PathVariable("idForm") String idForm)
{
try
{
Student item = registerService.get(id);
HttpHeaders respHeaders = new HttpHeaders();
//Change it with your real content type
MediaType mediaType = new MediaType("img","jpg");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
//I suppose you have a method "getFileName"
//By using attachment you download the file; by using inline you should see the image in the browser
respHeaders.setContentDispositionFormData("attachment", item.getFileName());
InputStreamResource isr = new InputStreamResource(new ByteArrayOutputStream(item.getData()));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Error; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Angelo

MVC 5 Delete Action in Details Page

In this MVC5 project, I want my Details page to also serve as Edit page and Delete page.
I'm tackling this task by creating 2 forms, one with everything needed to update the data, including the submit button.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.EmpresaID)
...
<input type="submit" class="btn btn-primary" value="Submeter" />
}
Now, for my second form, I basicly have a Delete button:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.EmpresaID)
<input type="submit" class="btn btn-danger" value="Delete" />
}
Error:
The parameters dictionary contains a null entry for parameter 'id' of
non-nullable type 'System.Int32' for method
'System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult]
DeleteConfirmed(Int32)'
I tried to use a ActionLink, but then I get a HTTP 404. Which is odd, since I am being sent to the correct destination:
#Html.ActionLink("Delete", "Delete", new { id = Model.EmpresaID })
Sends to
.../Empresa/Delete/6
EDIT1
Action Method:
// POST: Empresa/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Empresa empresa = await db.Empresas.FindAsync(id);
db.Empresas.Remove(empresa);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
EDIT2
Action Method
// POST: Empresa/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Delete([Bind(Include = "EmpresaID,Nome,Estado,Severidade,Inicio,Fim")] Empresa empresa)
{
//Do something with the posted viewModel
Empresa e = await db.Empresas.FindAsync(empresa.EmpresaID);
db.Empresas.Remove(e);
return RedirectToAction("Index");
}
Details.cshtml:
#using (Html.BeginForm("Delete", "Empresa", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.EmpresaID)
#Html.ActionLink("Delete", "Delete", new { id = Model.EmpresaID })
<button type="submit" class="btn btn-danger" value="Delete">Delete</button>
}
The ActionLink does not show any errors, but it doesn't delete anything either.
The Button gives me a HTTP 404. What am I doing wrong here?
EDIT3
// POST: Empresa/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Delete([Bind(Include = "EmpresaID,Nome,Estado,Severidade,Inicio,Fim")] Empresa empresa)
{
//Do something with the posted viewModel
Empresa e = await db.Empresas.FindAsync(empresa.EmpresaID);
db.Empresas.Remove(e);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
The only problem with EDIT2 was that I forgot to save the changes.
It's now working properly.
You need to tell the form which action to complete along with the FormMethod i.e. GET or POST. So for your delete action for example, something like this:
#model MyProject.SomeViewModel
#using (Html.BeginForm("Delete", "Empresa", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.EmpresaId)
<button type="submit" class="btn btn-danger" value="Delete">Delete</button>
}
And then in your controller something like:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(SomeViewModel viewModel)
{
//Do something with the posted viewModel
return RedirectToAction("Index");
}
// EmpressasController
// POST: Empresas/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
var empresa = _db.Empresas.Find(id);
if (empresa != null) _db.Empresas.Remove(empresa);
_db.SaveChanges();
return RedirectToAction("Index");
}
// Razor View
#using (Html.BeginForm("Delete", "Empresas", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.EmpresaId)
<button type="submit" class="btn btn-danger">Delete</button>
}

how to delay ajax response - asp.net mvc using partialview

My drop down list data are being passed to the controller using ajax helper in the view and in the controller, the partial view is returned using those data. When I run the application to see the partial view, it throws an error:
An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
However, when I debug it slowly, partial view is correctly shown in the page.
I assume that since the partial view is correctly shown as I intended in debug mode, I probably need to delay the response for ajax? Is this the right approach? Any ideas?
View:
#using (Ajax.BeginForm("GetEmployee", "Employee", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "showResult"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2" for="CountryId">Country</label>
<div class="col-md-10">
#Html.DropDownList("CountryId", null, "-- Select Country --", new { #class = "form-control", #onchange = "FillCity()" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="City">City</label>
<div class="col-md-10">
#Html.DropDownListFor(m => m.City, new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"), "-- Select City --", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Search" class="btn btn-default" />
</div>
</div>
</div>
}
<div id="showResult"></div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script>
function FillCity() {
var countryId = $('#CountryId').val();
$.ajax({
url: '/Posting/FillCity',
type: "GET",
dataType: "JSON",
data: { country: countryId },
success: function (cities) {
$("#City").html(""); // clear before appending new list
$("#City").append($('<option>-- Select City --</option>'))
$.each(cities, function (i, city) {
$("#City").append($('<option></option>').val(city.CityId).html(city.CityName));
});
}
});
}
</script>
}
Controller:
[HttpPost]
public ActionResult GetEmployee(int CountryId, int city)
{
var model = db.Employees
.Where(x => x.Country.CountryId == CountryId && x.City.CityId == city);
return PartialView("PartialEmployee", model);
}
PartialView:
#model IEnumerable<PokeGoTradeModel.Models.Employee>
<table class="table">
<tr>
<th>Country</th>
<th>City</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Country.CountryName)</td>
<td>#Html.DisplayFor(modelItem => item.City.CityName)</td>
</tr>
}
</table>
Here is my inner exception stack trace:
at System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
I figured it out. It was all because of lazy-loading. So my employee model has navigation properties of Country and City. In my Actionresult GetEmployee method, I needed to add more lines that includes navigation properties for employee model. So for example,
var model = db.employees.Include(x=>x.Country)
.Include(x=>x.City)
.Where(x=>x.Country.CountryId=countryId && x.City.CityId=cityId);
Hope it can help others if you have similar issues when using ajax for partial view. If you used virtual property in your model, for example:
public virtual Country Country { get; set; }
make sure you use Include in your query.

Ajax return form modelattribute

I have the following situation. In controller in method viewUserReminders I pass remindersListWrapper to my uReminder.jsp page.
#RequestMapping(value = "/user/reminders", method = RequestMethod.GET)
public ModelAndView viewUserReminders(Model model, #ModelAttribute("id_users") Long id_users) throws Exception {
ModelAndView mv = new ModelAndView();
mv.setViewName("user/uReminders");
List<Reminders> remindersList=userService.getUserReminders(id_users);
RemindersListWrapper remindersListWrapper=new RemindersListWrapper();
remindersListWrapper.setRemindersList(remindersList);
mv.addObject("remindersListWrapper", remindersListWrapper);
return mv;
}
In my uReminders.jsp file I have a form with modelattribute remindersListWrapper. This jsp page displays table of reminders. Next to every reminder there is a checkbox. The user can check several checkboxes, click button("Mark as read") and using Ajax I submit form and go to controller method
readReminders().
uReminders.jsp
<form:form action="/user/ajax/reminders/readReminders" method="POST" modelAttribute="remindersListWrapper" id="remindersForm">
<div id="main">
<table class="table">
<thead>
<tr>
<th></th>
<th></th>
<th>Reminder</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<c:forEach items="${remindersListWrapper.remindersList}" varStatus="status" var="reminders">
<tr id="row">
<td><form:hidden path="remindersList[${status.index}].idCalendar"/></td>
<td><form:checkbox path="remindersList[${status.index}].isRead"/></td>
<td><form:input path="remindersList[${status.index}].endDate"/></td>
</tr>
</c:forEach>
</c:when>
<c:when test="${empty remindersListWrapper.remindersList}">
<tr>
<td colspan="3">You have no reminders.</td>
</tr>
</c:when>
</c:choose>
</tbody>
</table>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<input type="button" id="reminders" value="Mark as read"/>
</c:when>
</c:choose>
</div>
</form:form>
$(window).load(function () {
$("#reminders").click(function () {
sendAjax('readReminders', $("#remindersForm").serialize());
});
});
In this method I save read reminders and I build newRemindersListWrapper with the new list of reminders(I want to delete checked reminders and display only unchecked). My first question is: How to return to the page newRemindersListWrapper itself.
#RequestMapping(value = "/user/ajax/reminders/readReminders", method = RequestMethod.POST)
#ResponseBody
public String readReminders(#ModelAttribute("remindersListWrapper") RemindersListWrapper remindersListWrapper, #ModelAttribute("id_users") Long id_users) throws Exception {
for(Reminders reminders:remindersListWrapper.getRemindersList()){
if(reminders.getIsRead()){
userDao.saveReadReminders(reminders);
}
}
RemindersListWrapper newRemindersListWrapper=new RemindersListWrapper();
///////////////////
here I want to return the newRemindersListWrapper itself
//////////////////
}
And my second question is: How I can set newRemindersListWrapper as modelattribute in my form.
function sendAjax(ref, data) {
console.log(data);
$.ajax({
url: 'ajax/reminders/' + ref,
type: 'POST',
data: data,
success: function (response) {
////////////////////////////////
I want to get newRemindersListWrapper and set it as modelattribute in form.
////////////////////////////////
console.log("success");
},
error: function (request, status, error) {
console.log('error ' + ref + ' text=' + request.responseText + ' status = ' + status + ' error = ' + error);
}
});
}
Question 1: just change the return type to RemindersListWrapper and return it
Question 2: Since you are using ajax, you can't. You need to use javascript to parse the returned list and update the page as needed.

Object not set to instance of object in Azure Emulator Model View

I have an exception caused by a direct copy of another code which follows:
Controller:
public PartialViewResult Pictures()
{
picturesList.Clear();
CloudTable table = _Service.GetCloudTable();
CloudBlobContainer blob = _Service.GetCloudBlobContainer();
TableQuery<PictureEntity> query = new TableQuery<PictureEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "hiltihaningepictures"));
foreach (PictureEntity pic in table.ExecuteQuery(query))
{
picturesList.Add(pic);
}
picturesList.Sort();
return PartialView();
}
View:
#model List<WebRole.Models.PictureEntity>
<script type="text/javascript" src="~/Scripts/jquery.liquid-slider.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.touchSwipe.min.js"></script>
<script type="text/javascript">
$(function () {
$('#main-slider').liquidSlider({
height: '525px',
minHeight: '525px',
dynamicArrows: true,
dynamicArrowsGraphical: true,
autoHeight: false,
continuous: true,
autoSlide: true,
pauseOnHover: true
});
});
/* If you need to access the internal property or methods, use this:
var api = $.data( $('#slider-id')[0], 'liquidSlider');
*/
</script>
<div id="main_liquid" style="display: none;">
#foreach (var item in Model)
{
<div class="liquid-slider" id="main-slider">
<div>
<img src="#item.Url" class="intro_img_group" />
<p>Uppladdad av: #item.Uploader, #item.Timestamp.DateTime</p>
<p>Beskrivning: #item.Description</p>
</div>
</div>
}
The only difference is that the other view, which work just fine and dandy, doesn't contain the Javascript section. Other than that completely identical.
Exception details:
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=App_Web_v2igssw5
StackTrace:
at ASP._Page_Views_Home_Pictures_cshtml.Execute() in g:\HiltiHaninge\HiltiHaninge\Views\Home\Pictures.cshtml:line 23
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
It's recommendening me to use keyword new but I dont' know what to do

Resources