I am trying to get the selected row of a MVCGrid and display the details in an modal dialog using a partialview.
I am getting the selected row via ajax:
$(document).ready(function(){
var selectedRow;
$(document).on('click', '.grid-mvc', function () {
pageGrids.PersonGrid.onRowSelect(function (e) {
// $.prompt(e.row.ID);
SendData(e.row);
});
});
});
The 'SendData'-function is:
function SendData(i) {
var data= i.ID;
$.ajax({
url: '/Home/Person',
contentType: "application/html; charset=utf-8",
type: "GET",
data: { "id": daten },
dataType: "html"
, success: function () {
ShowPersonDetails(data);
}
});
}
and the ShowPersonDetails(data) is like that:
function ShowPersonDetails(data) {
$(document).ready(function () {
$('#PersonDiv').load("Person?id=" + data);
$("#PersonDiv").prompt(
$("#PersonDiv").html(),
{
title: "some title",
buttons: { OK: 'true', Abbruch: 'false' },
position: { width: 800, height: 600 }
});
});
}
The controller:
[HttpGet]
public ActionResult Person(int id)
{
var pS = new DbAccess(MvcApplication.Connection).GetUserData(id);
var p = new Person();
if (pS.Rows.Count < 0)
{
return PartialView("Person");
}
p.Alter = pS.Rows[0].ItemArray[0].ToString();
p.Nachname = pS.Rows[0].ItemArray[5].ToString();
return PartialView("Person", p);
}
Any advice would be nice!
Greetings
PP
i did something like you are trying to do, so hope my code helps
in the grid, table, i put a link for details
<tr>
<td>
#Html.ActionLink("Details", "ActionDetails", new { id = Model.LstItems[x].ID }, new { #class = "detailsLink" })
</td>
</tr>
the javascript
$('#detailsDialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: {
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".detailsLink").button();
$(".detailsLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#detailsDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//open dialog
dialogDiv.dialog('open');
});
return false;
});
in somewhere in the view
<div id="detailsDialog" title="Offer Details">
</div>
the controller
public ActionResult ActionDetails(int id)
{
ItemEntity model = ItemEntity .GetBy(id);
return PartialView(model);
}
the partial view
#model YourNameSpace.Entities.ItemEntity
#using (Ajax.BeginForm("ActionDetails", "YourController", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "updateSuccess",
OnFailure = "showErrorMessage"
}, new { #id = "detailForm" }))
{
//your details for your item
}
hope this help you
Related
I have a pop up form from which new data can be added or old data can be updated.
But I don't know how to write method for this condition. I mean in the case of new data entry I don't need the Id but in case of edit I need the Id attribute. The controller name is Vehicle.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddorEdit([Bind(Include = "Id,VehicleType,Amount,RenewPeriod,Status")] Vehicle vehicle)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
if (ModelState.IsValid)
{
db.Vehicle.Add(vehicle);
db.SaveChanges();
}
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
The jquery code of index page from where pop up is called ::
<a class="btn btn-success" style="margin-bottom:10px;" onclick="PopupForm('#Url.Action("AddorEdit", "Vehicles")')"><i class="fa fa-plus"></i> Add New</a>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#tbl_vehicle").DataTable({
"ajax":{
"url": "/Vehicles/GetVehicle",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "VehicleType" },
{ "data": "Amount" },
{ "data": "RenewPeriod" },
{ "data": "RegisteredDate" },
{ "data": "RegisteredBy" },
{ "data": "Status" },
{ "data": "ModifiedBy" },
{ "data": "ModifiedDate" }
],
"language": {
"emptyTable" : "No data available, please click on <b>Add</b> button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url).done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: 'fill details',
height: 500,
width: 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
alert("testing....");
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (date) {
if(data.success)
{
Popup.dialog('close');
dataTable.ajax.reload();
}
}
});
return false;
}
</script>
An easy way to handle this by making id as a HiddenField so when ever user post data to the server you can query the id field.
whether it has value or not and decide which operation you should perform i.e. Add operation if id is null/empty and Edit Operation if Id has the value.
Please use below code section for reference :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddorEdit([Bind(Include = "Id,VehicleType,Amount,RenewPeriod,Status")] Vehicle vehicle)
{
if (ModelState.IsValid)
{
if(vehicle.Id <= 0)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
db.Vehicle.Add(vehicle);
}
else
{
db.Entry(vehicle).State = EntityState.Modified;
//perform more checks if you want
}
db.SaveChanges();
}
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
You can achieve it by this simple way
if (ModelState.IsValid)
{
if(vehicle.Id <= 0)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
db.Vehicle.Add(vehicle);
}
else
db.Entry(vehicle).State = EntityState.Modified;
db.SaveChanges();
}
I am trying to populate form items based on a dropdown selection without refreshing the entire page or loading a new view. This was fairly simple in web forms using an UpdatePanel, for instance. However, I can't get this to work in MVC.
I've tried many of the solutions I could find. I don't know if this is a DotNetNuke issue.
Debugging shows the controller firing and retrieving a record but the form items are never populated.
I've tried both a jquery.post and an .ajax call. Neither work.
View:
#inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<IMS.Model.lh.Associations>
#using IMT.LH.AssociationAdmin.Models
#using IMS.Model.lh
#{
ViewBag.Title = "Association";
}
<h2>Association</h2>
<div id="Associations-#Dnn.ModuleContext.ModuleId">
#Html.DropDownList("SelectAssociation")
</div>
<div id="Association-#Dnn.ModuleContext.ModuleId">'
#Html.LabelFor(m=>m.AssociationID)<br />
#Html.Label("Title")<br />
#Html.Label("Slug")<br />
#Html.Label("Description")<br />
#Html.Label("Tagline")<br/>
</div>
<script type="text/javascript">
const rvtoken = $("input[name='__RequestVerificationToken']").val();
const moduleId = #Dnn.ModuleContext.ModuleId;
const tabId = #Dnn.ModuleContext.TabId;
$.ajaxSetup({
headers: {
"RequestVerificationToken": rvtoken
}
});
$('#SelectAssociation').change(
function() {
$.post(
"/DesktopModules/MVC/LH.AssociationAdmin/Association/SelectAssociation",
{
id: $(this).val()
}),
function() {
alert("success");
}
/*$.ajax({
url: "/DesktopModules/MVC/LH.AssociationAdmin/Association/SelectAssociation",
method: "Post",
data: {
id: $(this).val()
},
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken
},
success: function() {
alert("success");
},
fail: function() {
alert("fail");
}
});
*/
});
</script>
Controller:
[HttpPost]
[DotNetNuke.Web.Mvc.Framework.ActionFilters.ValidateAntiForgeryToken]
public ActionResult SelectAssociation()
{
ModelState.Clear();
int id = Convert.ToInt32(Request.Form["id"]);
using (var ac = new AssociationsController())
{
ac.GetById(id);
return PartialView("Index", ac.CurrentRec);
}
}
Ok. One way I've found is to simply return a json object to the .ajax call and parse it:
$.ajax({
cache: false,
dataType: 'json',
url: "/DesktopModules/MVC/LH.AssociationAdmin/Association/SelectAssociation",
method: "Post",
data: {
id: $(this).val()
},
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken
},
success: function(data) {
//alert(data.AssociationID);
$('#AssociationID').text(data.AssociationID);
$('#Title').text(data.Title);
$('#Slug').text(data.Slug);
$('#Description').text(data.Description);
$('#Tagline').text(data.Tagline);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
console.log(jqXHR);
}
});
});
Controller:
[HttpPost]
[DotNetNuke.Web.Mvc.Framework.ActionFilters.ValidateAntiForgeryToken]
public ActionResult SelectAssociation()
{
ModelState.Clear();
int id = Convert.ToInt32(Request.Form["id"]);
using (var ac = new AssociationsController())
{
ac.GetById(id);
return Json(ac.CurrentRec);
//return PartialView("Index", ac.CurrentRec);
}
}
But, I am certainly open to other suggestions.
I have script for recording video
Here is code of it
var fileName;
stop.onclick = function () {
record.disabled = false;
stop.disabled = true;
window.onbeforeunload = null; //Solve trouble with deleting video
preview.src = '';
fileName = Math.round(Math.random() * 99999999) + 99999999;
console.log(fileName);
var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I try to get url with this row var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
and with this code write to table filename
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
but it not works.
There is my Action method for it
[HttpPost]
public ActionResult LinkWriter(string link, int id) {
Link link_ = new Link
{
Link1 = link,
Interwier_Id = id,
};
db.Link.Add(link_);
db.SaveChanges();
return View();
}
But it not works. Where is my mistake?
UPDATE
As I understood not works this
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I'm beginner in asp.net and highchart control,want to use highchart control in my web application web form,for that purpose read this tutorial:
this tutorial
and write this web service in my project:
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
cityPopulation cpData = new cityPopulation();
cpData.city_name = "tabriz";
cpData.population = 100;
p.Add(cpData);
return p;
}
that web service name is this:
WebService1.asmx
and in my web form write this script :
<script type="text/javascript">
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "WebService1.asmx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
//*
</script>
before that script write this code:
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script src="Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
and write this html code:
<select id="ddlyear">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select>
<button id="btnCreatePieChart">Show </button>
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
but when i run project and fire the button,can not see anything,and chart not show to me,what happen?is my code incorrect?how can i solve that problem?thanks.
i think ajax can not call the web service!
So I have some javascript code that sends data to my controller:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#newGrade").click(function () {
var newGradeName = $("#newGradeName").val();
var newGradeValue = $("#newGradeValue").val();
var vSchoolID = $("#SchoolID").val();
if (newGradeName != null && newGradeValue != null) {
$.ajax({
url: '#Url.Action("NewGrade", "School")',
data: { gradeName: newGradeName, gradeValue: newGradeValue, schoolID: vSchoolID },
type: 'POST',
traditional: true,
success: function (data) {
if (data.status)
window.location = data.route;
},
error: function () {
return false;
}
});
}
});
});
</script>
Controller:
public ActionResult NewGrade(String gradeName, Int32 gradeValue, Guid schoolID)
{
School school = schoolRepository.GetByID(schoolID);
school.Grades.Add(
new Grade
{
GradeID = Guid.NewGuid(),
Name = gradeName,
NumericalValue = gradeValue
});
schoolRepository.Update(school);
schoolRepository.Save();
if (Request.IsAjaxRequest())
{
var json = new { status = true, route = Url.RouteUrl(new { action = "Edit", id = schoolID }) };
return Json(json, JsonRequestBehavior.AllowGet);
}
return View();
}
My issue now is I want to return to my Edit page (possibly refreshing the page, but not the data, or just refresh the entire page), but my Edit page takes an ID (schoolID). Shown here when pressing the button to get to the Edit page:
<i class="icon-pencil"></i> Edit
Try window.location.href and see what happens.
success: function(data) {
if (data.status)
window.location.href = data.route;
},
This should work fine assuming you are getting a JSON reponse from your action method like
{"status":"true","route":"/School/Edit/1"}
where 1 is the ID of new record.