JQuery Dialog and multi Mvc4 PartialView - c#

i have a View, and on a button click i need that open me a JQueryDialog loaded from PartialView that have inside a list of items... on click of one of these items, i need that in the same JQueryDialog open another PartialView, for editing this item, so a simple List/Detail nested in a JQueryDialog..
i post a sample..
http://sdrv.ms/15hG92K
VIEW
$('#dialogReferences').dialog({
autoOpen: false,
width: dWidth,
resizable: false,
title: 'TEST',
modal: true,
draggable: false,
position: ['top', 100],
open: function (event, ui)
{
var id = $(this).data('id');
var url = '#Url.Action("ListItem", "Home")';
$(this).dialog().load(url, function ()
{
$(document).unbind("click", ".k-grid-Edit").on("click", ".k-grid-Edit", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlEdit = '#(Html.Raw(#Url.Action("ItemEdit", "Home", new { selectedId = "_selectedId_" })))';
urlEdit = urlEdit.replace("_selectedId_", selectedData.Id);
$('#dialogReferences').dialog().load(urlEdit);
}
});
$(document).unbind("click", ".k-grid-Delete").on("click", ".k-grid-Delete", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlDelete = '#(Html.Raw(#Url.Action("ItemDelete", "Home", new { selectedId = "_selectedId_" })))';
urlDelete = urlDelete.replace("_selectedId_", selectedData.Id);
$.ajax({
url: urlDelete,
type: 'POST',
cache: false,
dataType: 'json',
success: function (result)
{
if (result.success)
{
alert('DELETE');
grid.dataSource.read();
}
}
});
}
});
});
}
});
EDIT
$(document).ready(function ()
{
$.ajaxSetup({ cache: false });
$(document).unbind("click","#btnCancel").one("click", "#btnCancel", function (evt)
{
evt.preventDefault();
var model = #Html.Raw(Json.Encode(Model));
var urlList = '#Url.Action("ListItem", "Home")';
$('#dialogReferences').dialog().load(urlList, function ()
{
$(document).unbind("click", ".k-grid-Edit").one("click", ".k-grid-Edit", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlEdit = '#(Html.Raw(#Url.Action("ItemEdit", "Home", new { selectedId = "_selectedId_" })))';
urlEdit = urlEdit.replace("_selectedId_", selectedData.Id);
$('#dialogReferences').dialog().load(urlEdit);
}
});
$(document).unbind("click", ".k-grid-Delete").on("click", ".k-grid-Delete", function (evt)
{
evt.preventDefault();
var grid = $("#contactsGrid").data("kendoGrid");
var selectedData = grid.dataItem(grid.select());
if (selectedData)
{
var urlDelete = '#(Html.Raw(#Url.Action("ItemDelete", "Home", new { selectedId = "_selectedId_" })))';
urlDelete = urlDelete.replace("_selectedId_", selectedData.Id);
$.ajax({
url: urlDelete,
type: 'POST',
cache: false,
dataType: 'json',
success: function (result)
{
if (result.success)
{
alert('DELETE');
grid.dataSource.read();
}
}
});
}
});
});
})
});
if i try to 'open file dialog' and delete without edit, it call delete action one time, and it's ok.
but if you try to enter in edit and than come back with cancel to the list, and delete, it call twice.
Someone can give me and advice?

Related

Asp.net core MVC and JQuery submit

I have this code(JQuery) in my View:
$("form").submit(function (e) {
e.preventDefault();
var form = this;
var link = '#Url.Action("Action", "Controller")';
var args = {
MyFVal: MyFVal.val(),
MySVal: MySVal.val()
};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
alert(data.acces);
if (data.acces) {
AllEnable();
form.submit();
}
else {
alert(data.erromessage);
}
},
error: function () {
alert("Error. Kontaktujte správce.");
}
});
});
When I gets submitted then I have this if in my save action.
if (Request.Form.ContainsKey("Insert"))
{
// do code that is supposed to run
}
else if (Request.Form.ContainsKey("Edit"))
{
// do another code
}
My problem is that because I submitted form by JQuery this if and elseif never gets executed.
Thanks for any help!
You might want to pass value for your requirements in Action condition. See operationType sample parameter
var obj = {
UniqueId: modelUniqueId.val(),
Name: modelName.val(),
operationType: $("[name=operationType]").val()
};
$.ajax({
type: "POST",
url: '/hrms/Class/Index',
data: obj,
success: function (result) {
if (result.success == true) {
createAndProcessPageAlert("success", result.message);
}
else {
createAndProcessPageAlert("error", result.message);
}
And in your Controller \ Action
[HttpPost]
public JsonResult Index(string operationType, ClassModel model)
{
var result = new HttpResponseModel<ClassModel>();
var user = Request.GetUserProfile();
if (operationType == "add")

How to send data object which contain upload files and string to controller using ajax?

I am sending array of object which contain upload file data and some string values to my controller using ajax but it sending failed.
I also tried with formdata but no luck.I want to know how i send data to controller.
Jquery/View Code:
function SaveBrandDetail() {
debugger;
var data = new Array();
var tablecount = 0;
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"fileUpload": $(this).find(".fileUploadData").get(0).files[0]
};
data.push(row);
});
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify(data),
success: function (msg) {
},
error: function () {
}
});
}
Controller File:
public ActionResult SaveData(List<Data> data)
{
bool saved = false;
}
i expect to recieve data with upload file in my controller.i have declared HttpPostedFileBase in my modal class.
var formData = new FormData();
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"FileName": $(this).find(".fileUploadData").get(0).files[0].name
};
var file = $(this).find(".fileUploadData").get(0).files[0];
formData.append(file.name, file);
data.push(row);
});
formData.append("data", JSON.stringify(data));
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
data: formdata,
processData: false,
contentType: false,
success: function (msg) {
},
error: function () {
}
});
public ActionResult SaveData(string data)
{
var files = Request.Files;
List<Data> d = JsonConvert.Deserialize<List<Data>>(data);
foreach(var item in d)
{
var file = files[item.FileName];
}
bool saved = false;
}

dropdown list event MVC 5

I have a dropdownlist contains a list of products which binds from database. I want to load selected product Data.
here is my code in view
#Html.DropDownListFor(model => model.ProductName, new SelectList(Model.ProductsList, "ProductID", "ProductName"), new
{
id = "Productslist",
#class = "GreenDropDownListStyle",
#datastyle = "dropdown",
#onchange = "FillProduct()"
})
I had use java Script code to send select Product Id then get it's data
<script type="text/javascript">
$(document).ready(function () {
$("#Productslist").change(function () {
debugger;
var selectedIndex = $(this).val();
var divH = document.getElementById(selectedIndex);
if (selectedIndex > 0) {
$.ajax(
{
url: '/Inventory/ViewProduct',
type: 'GET',
data: { ProductID: selectedIndex },
contentType: 'application/json; charset=utf-8',
success: function (data) {
///
},
error: function () {
alert("error");
}
});
}
else {
divH.style.visibility = 'hidden'; // Hide
}
});
});
</script>
the issue that this code send the selected index not the is for the selected product also its send the id as a string so it never go to my condition
last thing in case of succeed what i should write
it solved by
var ProductID = this.value;

How to load new data after click next or back Fullcalendar

I am using Fullcalendar plugin which is integrated with my ASP.NET MVC project. My main task consists of creating a schedule of reservations. I have written the code which is responsible for displaying events("Buttons") for specific date, and it works fine!. Code below:
var calendar = $("#calendar").fullCalendar({
weekends: false
, lang: 'pl',
header: {
left:'',
center: 'title',
right: 'today prev,next'
}, height: 630, week: true, columnFormat: 'dd M/D', minTime: '8:00', maxTime: '20:00', selectable: true,
allDaySlot: false, eventColor: '#F6A828',
events: function (start, end, timezone, callback) {
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
},
})
$('#calendar').fullCalendar('changeView', 'agendaWeek');
and method GetEvents in C#
public JsonResult GetEvents()
{
if (Session["DoctorID"] == null)
{
return Json(new { redirectUrl = Url.Action("Terminarz", "Recepcjonista"), isRedirect = true });
}
var listEvent = new List<CallendarEvent>();
List<CallendarEvent> list = TermRepository.GetAllEventsByDoctorId((int)Session["DoctorID"]);
int licznik = 1;
foreach (var item in list)
{
int count = Size(item.id, item.From, item.To);
for (int i = 0; i < count; i++)
{
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30)
});
licznik++;
}
}
var listEvent2 = from l in listEvent
select new
{
id = l.id,
//day = l.day,
//Title = l.Title,
start = l.From,
end = l.To,
color = "#88CD23"
};
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and now I would like to handle next and back buttons and change start date, end +7 day. I wrote something like this, but doesn't work
C#
public JsonResult GetEventsAdd(int move)
{
//all the same method as in GetEvents, but added days
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddDays(move),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30).AddDays(move)
});
licznik++;
}
}
//all the same method as in GetEvents
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and script was changed
events: function (start, end, timezone, callback) {
var data = { "move": 7 }
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
//data: JSON.stringify(calendar),
//datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
$(".fc-next-button").one("click", function () {
$.ajax({
url: '/Dentist/GetEventsAdd/',
type: 'POST',
data: JSON.stringify(data),
datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//$('#calendar').fullCalendar('refetchEvents');
}
});
});
how can I get such a solution?
The AJAX call that fullcalendar makes passes the start and end date range for the current view. It will then call that again, only if it doesn't have the date stored.
so in your /Dentist/GetEvents/
grab the "GET" variables: "START" and "END".
return the events that are in that range.
then simply use the native 'next', 'prev' buttons from fullcalendar and let it do its thing.

asp.net MVC pass server value to hidden field

From my OnePageCheckout.cshtml View i call ajax controller
#Html.Hidden("StepContent", (string)ViewBag.newAddress) #* never work *#
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: this.nextStep, // still stay in the same page
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
public ActionResult OpcSaveBilling(FormCollection form) {
ViewBag.newAddress="abc";
return Json(new {
update_section = new UpdateSectionJsonModel() {
name = "confirm-order",
html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel)
},
goto_section = "confirm_order"
});
}
How can I update the status of the hidden input with a value from the controller?
UPDATE 2:
var Billing = {
form: false,
saveUrl: false,
init: function (form, saveUrl) {
this.form = form;
this.saveUrl = saveUrl;
},
save: function () {
if (Checkout.loadWaiting != false) return;
Checkout.setLoadWaiting('billing');
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: function (data) {
this.nextStep; << nextStep won't be called !! but it works for success: this.nextStep
},
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
},
resetLoadWaiting: function () {
Checkout.setLoadWaiting(false);
},
nextStep: function (response) {
alert('aa');
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
$('#StepContent').val($("#billing-address-select").find('option:selected').text());
Checkout.setStepResponse(response);
}
};
Change status in JS after ajax call,
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: function (data) {
$("#StepContent").val(data.status);
this.nextStep;
},
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
and controller pass status in JSON
public ActionResult OpcSaveBilling(FormCollection form) {
ViewBag.newAddress="abc";
return Json(new {
update_section = new UpdateSectionJsonModel() {
name = "confirm-order",
html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel),
},
status = "abc",
goto_section = "confirm_order"
});
}

Categories

Resources