customize popup window in telerik grid in mvc - asp.net

i have to display customize popup window in telerik grid because i cannot display all values in grid so i want when user click on grid edit button and according to particular row datakey
fetch data from table and display those records in popup window and i want to open that window when user click on grid button not on my checkout button so what can i do
view
<%# Page Title="" Language="C#" MasterPageFile="~/Content/JobSeekers.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<ITClassifieds.ViewModels.workexperience>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
trial
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function onRowSelected(e) {
var ordersGrid = $('#Grid').data('tGrid');
var resexpid = e.row.cells[0].innerHTML;
// update ui text
$('#rexsepid').text(resexpid);
// rebind the related grid
// ordersGrid.rebind({
// resexpid: resexpid
// });
var window = $("#Window").data("tWindow");
window.center().open();
}
function closeWindow() {
var window = $("#Window").data("tWindow");
window.close();
var undoButton = $('#undo');
undoButton.show();
}
function openWindow() {
var window = $("#Window").data("tWindow");
window.center().open();
// var ordersGrid = $('#Grid').data('tGrid');
// var resexpid = ordersGrid.row.cells[0].innerHTML;
// $('#rexsepid').text(resexpid);
// alert(resexpid);
}
function viewDetails(activityId) {
//....Do stuff here...
alert(activityId);
}
</script>
<h2>trial</h2>
<%=Html.Telerik().Grid(Model).Name("Grid").DataKeys(keys => keys.Add(m => m.resexpid))
.Columns(columns=>
{
columns.Bound(m => m.resexpid).Width(100);
columns.Bound(m => m.company).Width(100);
//columns.Bound("Title").Width(100);
columns.Bound(m=>m.title).Width(200);
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Text);
commands.Delete().ButtonType(GridButtonType.Text);
}).Width(200).Title("Command");
columns.Bound(m => m.resexpid).ClientTemplate("<a onclick='viewDetails('" + "'<#= Id #>'" + "');' href='javascript:'>View</a>").Title("View");
//columns.Bound(m => m.Date).Width(200);
})
.ClientEvents(events => events.OnRowSelect("onRowSelected"))
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("_FirstLook","Editresume")
.Update("_SaveAjaxEditing", "Editresume")
.Delete("_DeleteAjaxEditing", "Editresume");
})
.Scrollable(scrolling => scrolling.Enabled((bool)ViewData["scrolling"]))
.Sortable(sorting => sorting.Enabled((bool)ViewData["sorting"]))
.Pageable(paging => paging.Enabled((bool)ViewData["paging"]))
.Filterable(filtering => filtering.Enabled((bool)ViewData["filtering"]))
.Groupable(grouping => grouping.Enabled((bool)ViewData["grouping"]))
.Footer((bool)ViewData["showFooter"])
.RowAction(row => row.Selected = row.DataItem.resexpid.Equals(ViewData["id"]))
%>
<button class="button medium gray" onclick="openWindow()">Checkout</button>
<% Html.Telerik().Window()
.Name("Window")
.Title("Update Option")
.Draggable(false)
.Resizable(resizing => resizing
.Enabled(true)
.MinHeight(250)
.MinWidth(250)
.MaxHeight(500)
.MaxWidth(500)
)
.Scrollable(true)
.Modal(true)
.Buttons(b => b.Maximize().Close())
.Content(() =>
{%>
<div>
<%-- <% %>
<% if (ResumePackgeExits == true && JobPackageExist == true)
{
}
else if (ResumePackgeExits == false && JobPackageExist == true)
{
%>--%>
<div>
<table border="1" cellpadding="5" cellspacing="0" bordercolor="#CCCCCC" style="font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;border:1px solid #AAA;margin:5px;">
<tr> <td colspan="3">
We Are also Provied a Unlimeted Resume Subscription.
if You Want a Resume Subscription Please click on RESUME Package button.
</td></tr>
</table>
<br />
<%=Html.ActionLink("RESUME Package", "ResumePackage", null, new { #class = "button medium gray" })%>
</div>
<%--<%}else if(ResumePackgeExits == true && JobPackageExist == false)
{%>
--%>
<div>
<table border="1" cellpadding="5" cellspacing="0" bordercolor="#CCCCCC" style="font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;border:1px solid #AAA;margin:5px;">
<tr>
<td colspan="3">
We Are also Provied a Job Subscription.
if You Want a Job Subscription Please click on JOB Package button.
</td>
</tr>
</table>
<br />
<%=Html.ActionLink("JOB Package", "jobpackage", null, new { #class = "button medium gray" })%>
</div>
<%-- <%} %>--%>
<br />
<%-- <% using (Html.BeginForm("Checkout", "Package", FormMethod.Post, new { name = "frmDCC", onsubmit = "return CheckForm();" }))
{ %>
<input type="hidden" value="<%= Model.Total%>" name="totalPayment" />
<table>
<tr>
<td><%=Html.RadioButton("paymentoption","paypalPayment") %></td>
<td><img src='https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif' border='0' align='top' alt='Check out with PayPal' /></td>
</tr>
<tr>
<td><%=Html.RadioButton("paymentoption","CreditCart") %></td>
<td> <img src="https://www.paypal.com/en_US/i/bnr/horizontal_solution_PPeCheck.gif" border="0" alt="Check out with Credit Cart" /></td>
</tr>
</table>
<input type="submit" value="Go" name="submit" class="button medium gray" />
<%} %>
--%>
</div>
<%})
.Width(500)
.Height(400)
.Visible(false)
.Render();
%>
</asp:Content>
controller
public ActionResult trial()
{
//var re = (from j in db.Resumes
// select new
// Jobresults { JobTitle = j.JobTitle, Company = j.CompanyInfo }).AsEnumerable();
var re = (from j in db.Resumes join res in db.Res_Exp on j.ResumeID equals res.Resume.ResumeID
where j.ResumeID == 258
select new workexperience {title=j.ResumeTitle,company=j.DesiredCompany ,resexpid=res.ResExpID}
).AsEnumerable();
ViewData["ajax"] = true;
ViewData["scrolling"] = true;
ViewData["paging"] = true;
ViewData["filtering"] = true;
ViewData["grouping"] = true;
ViewData["sorting"] = true;
ViewData["showFooter"] = true;
return View(re);
}

In order to make customized popup in telerik grid you need to exploit editor templates. You will make an editor template for your viewmodel. this brad wilson's tutorial will help you to get start. this post at telerik forum may also help you also

Related

Inserting data using ado.net via ajax

i am having trouble in finding the problem. I was inserting product record via ado.net and it worked fine. Now i tried ajax for doing it in a more better way . but i am having trouble since the code never runs the function intended to run when i click button via ajax. so need ur help. Thanks. here is the code:
//this is my home.aspx page
$(document).ready(function () {
$("#submit").click(function () {
alert("you clicked");
$.ajax({
type: "POST",
contentType: "application/json",
url: "home.aspx/insert",
dataType: "json",
// data: "{'Name':'" + document.getElementById('name').value + "'}",
data:"{}",
//async: false,
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
})
});
</script>
//////////////////////////////////
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><label>Product Name</label></td>
<td> <asp:TextBox runat="server" id="name"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product Code</label></td>
<td><asp:TextBox runat="server" id="code"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product Category</label></td>
<td><asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Gadgets</asp:ListItem>
<asp:ListItem>Vehicles</asp:ListItem>
<asp:ListItem>Garments</asp:ListItem>
<asp:ListItem>Eatables</asp:ListItem>
<asp:ListItem>Furniture</asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td><label>Expiry date</label></td>
<td><asp:TextBox runat="server" TextMode="Date" id="dt"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product price</label></td>
<td><asp:TextBox runat="server" id="price"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product Image</label></td>
<td> <asp:FileUpload ID="file_image" runat="server" /></td>
<td> </td>
<td><asp:Label runat="server" id="showtext"></asp:Label></td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td></td>
<%--<asp:Button runat="server" OnClick="submit" Text="Submit" BackColor="White" Width="100px" />--%>
<td> <input type="button" style=" width:100px;" value="Submit" id="submit" /> </td>
</tr>
</table>
</div>
<asp:Label ID="res" runat="server"></asp:Label>
</form>
///////////////////////////////////////////////
//this is my home.aspx.cs page :
public void insert()
{
if (file_image.HasFile)
{
string ext = System.IO.Path.GetExtension(file_image.FileName);
if (!ext.Equals(".jpg"))
{
showtext.Text = "Please select correct file format i.e jpg or jpeg";
showtext.ForeColor = System.Drawing.Color.Purple;
}
else
{
file_image.SaveAs(Server.MapPath("~/Uploads/" + file_image.FileName));
showtext.Text = "File uploaded";
showtext.ForeColor = System.Drawing.Color.Green;
productclass pc = new productclass();
pc.Pr_name = name.Text;
pc.Code = code.Text;
pc.Category = DropDownList1.SelectedValue;
pc.Expiry = Convert.ToDateTime(dt.Text);
pc.Price = Convert.ToInt32(price.Text);
pc.Pr_image = file_image.FileName;
dalinsert di = new dalinsert();
bool flag = di.insert(pc);
if (flag.Equals(true))
{
res.Text = "data inserted";
//Thread.Sleep(10000);
// Response.Redirect("home.aspx");
}
else
{
res.Text = "issue in inserting data";
}
}
}
else
{
showtext.Text = "Please select file";
showtext.ForeColor = System.Drawing.Color.Red;
}
}

how to transfer data from controller to view

HomeController.cs
[HttpPost]
public ActionResult Index(int searchtext)
{
var data = (from pm in db.ProductMasters
join shi in db.SuppliersHotelsInfoes
on pm.ProductID equals shi.LocHotelID
where shi.SearchID == searchtext
select new {pm.ProductId,pm.Image,shi.HotelName,shi.HotelPrice}).ToList().Take(10);
ViewBag.Data = data;
return View();
}
Transfering the data to the view
<% try { %>
<tr><td>
<% foreach(var item in ViewBag.Data){ %>
<img alt="" src="<%= item. %>" />
</td><%} %> <% foreach(var item in ViewBag.Data) { %>
<td><%: Html.DisplayFor(modelItem => "")%></td>
<td><%: Html.DisplayFor(modelItem => "")%> </td>
<td><%: Html.DisplayFor(modelItem => "")%></td>
</tr>
<%} }%>
<%catch(Exception ex){ }%>
Here, how to get the values in "var item"
You really should use a ViewModel, I can't remember last time I used the ViewBag
I'm also going to use Razor here, its syntax is much more terse. You don't need to use DisplayFor if you're just presenting the data:
#foreach(var item in ViewBag.Data){
<tr>
<td><img alt="" src="#item.Image" /><td>
<td>#item.ProductId</td>
<td>#item.HotelName</td>
<td>#item.HotelPrice</td>
</tr>
}

How to validate dropdown in asp.net mvc2.0?

I am using asp.net mvc 2.0.I have to validate my dropdownlist after clicking save button.
this is my view code.
<%using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "Save" }))
{
%>
<table>
<tr>
<td>
<%:Html.TextBoxFor(m => m.EmployeeName)%>
</td>
</tr>
<tr>
<td>
<%:Html.DropDownListFor(m => m.ProjectModel, new SelectList(Model.ProjectModel, "Id", "ProjectName"), new { #id = "ddlProject"})%>
</td>
</tr>
<tr>
<td>
<input id="btnSave" type="button" value="Save" />
</td>
</tr>
</table>
<center>
<div id="result">
<%Html.RenderPartial("~/Views/PartialViews/partialpage.ascx");>
</div>
</center>
</table>
<%} %>
and my java script code is:
$(document).ready(
function () {
$('#btnSave').click(function () {
$.ajax(
{
cache: false,
async: true,
type: "POST",
url: $('#Save').attr('action'),
data: $('#Save').serialize(),
success: function (data) {
$('#result').html(data);
},
error: function (data) {
}
});
});
});
here am using
input type="button"
because i have to return partial view after submit save button.
can anyone tell how to validate my dropdown??
I write this as follow in Asp.Net Mvc4. I think that perhaps it is same in Mvc2.
#Html.DropDownListFor(model => model.Contract.ContractStatusId, new SelectList(Model.ContractStatus, "ContractStatusId", "Name"), "-- Select Status --", new { data_form = "select2", #style = "width: 200px;" })
#Html.ValidationMessageFor(model => model.Contract.ContractStatusId)

ASP.NET MVC: How to call javascript function in Html.ActionLink

When I edit single recored in page, I use checkbox to get a selected row not every row with an actionlink element, but it seemed I cant make this way happen through calling javascript code (function GetSelectedRow() should return an id). Could anyone have a nice idea?
<head runat="server">
<title>Index</title>
<script type="text/javascript" language="javascript">
function GetSelectedRow() {
var a = 0;
var chkBoxes = document.getElementsByName("chkSelect");
var count = chkBoxes.length;
for (var i = 0; i < count; i++) {
if (chkBoxes[i].checked == true)
a = chkBoxes[i].primaryKeyID;
}
return a;
}
</script>
</head>
<body>
<div>
<span style="width:20%">
<%: Html.ActionLink("Add", "Create")%>
</span>
<span>
<%: Html.ActionLink("Edit", "Edit", new { id = GetSelectedRow()) %>
</span>
<span>
<%: Html.ActionLink("Detial", "Details", new { id = GetSelectedRow() })%>
</span>
<span>
<%: Html.ActionLink("Delete", "Delete", new { id = GetSelectedRow()) %>
</span>
</div>
<table>
<tr>
<th></th>
<th>
CategoryID
</th>
<th>
CategoryName
</th>
<th>
Description
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink("Details", "Details", new { id = item.AppCategoryID })%>
</td>
<td>
<%: Html.CheckBox("chkSelect", false, new { primaryKeyID = item.AppCategoryID })%>
</td>
<td>
<%: item.AppCategoryID %>
</td>
<td>
<%: item.AppCategoryName %>
</td>
<td>
<%: item.Description %>
</td>
</tr>
<% } %>
</table>
</body>
You could do something like this:
<script type="text/javascript">
function RedirectUsingSelectedRow() {
var id = GetSelectedRow();
window.location = '../Controller/Details/' + id;
}
</script>
Edit
Mixing server and client that way won't work. What you need to do, when a row is selected, is to manipulate the URL. So rather than return a URL, have GetSelectedRow do:
function GetSelectedRow() {
//existing logic minus return
var link1 = document.getElementById("Link1"); //this would require giving links an ID
link1.href = '<%= Url.Action("Detail", new { controller = "Details" }) %>' +
'id=' a.toString();
}
You have to change it from client-side javascript is the key, rather than doing that during the rendering process.
HTH.
Try this -
$('#GetSelectedRow').click(function() { /* Your Code */ });
Calling java script function by id 'GetSelectedRow'. Instead of calling the function by id, you can directly call the function
<% Html.ActionLink("Edit", "Edit", "Controller", new { onclick = "GetSelectedRow();"}) %>

ASP.NET MVC 2 - Saving child entities on form submit

I'm using ASP.NET MVC 2 and am struggling with saving child entities. I have an existing Invoice entity (which I create on a separate form) and then I have a LogHours view that I'd like to use to save InvoiceLog's, which are child entities of Invoice. Here's the view:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TothSolutions.Data.Invoice>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Log Hours
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$("#InvoiceLogs_0__Description").focus();
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Log Hours</h2>
<% using (Html.BeginForm("SaveHours", "Invoices")) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<table>
<tr>
<th>Date</th>
<th>Description</th>
<th>Hours</th>
</tr>
<%
int index = 0;
foreach (var log in Model.InvoiceLogs) {
%>
<tr>
<td><%: log.LogDate.ToShortDateString() %></td>
<td><%: Html.TextBox("InvoiceLogs[" + index + "].Description")%></td>
<td><%: Html.TextBox("InvoiceLogs[" + index + "].Hours")%></td>
<td>Hours</td>
</tr>
<%
index++;
}
%>
</table>
<p>
<%: Html.Hidden("InvoiceID") %>
<%: Html.Hidden("CreateDate") %>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
And here's the controller code:
//GET: /Secure/Invoices/LogHours/
public ActionResult LogHours(int id)
{
var invoice = DataContext.InvoiceData.Get(id);
if (invoice == null)
{
throw new Exception("Invoice not found with id: " + id);
}
return View(invoice);
}
//POST: /Secure/Invoices/SaveHours/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveHours([Bind(Exclude = "InvoiceLogs")]Invoice invoice)
{
TryUpdateModel(invoice.InvoiceLogs, "InvoiceLogs");
invoice.UpdateDate = DateTime.Now;
invoice.DeveloperID = DeveloperID;
//attaching existing invoice.
DataContext.InvoiceData.Attach(invoice);
//save changes.
DataContext.SaveChanges();
//redirect to invoice list.
return RedirectToAction("Index");
}
And the data access code:
public static void Attach(Invoice invoice)
{
var i = new Invoice { InvoiceID = invoice.InvoiceID };
db.Invoices.Attach(i);
db.Invoices.ApplyCurrentValues(invoice);
}
In the SaveHours action, it properly sets the values of the InvoiceLog entities after I call TryUpdateModel but when it does SaveChanges it doesn't update the database with the new values. Also, if you manually update the values of the InvoiceLog entries in the database and then go to this page it doesn't populate the textboxes so it's clearly not binding correctly.
Thanks,
Justin
Got it working, I needed to populate the InvoiceLogID and InvoiceID in hidden fields so they'd get populated in the EntityCollection.

Resources