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();"}) %>
Related
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>
}
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)
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
How can I update a complex model? I have the following View:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Tidrapportering.Models.Week>" %>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<table width="100%">
<% foreach (var task in Model.Tasks)
{ %>
<tr>
<td>
<%: task.Customer.CustomerName %>
</td>
<td>
<%: task.TaskName %>
</td>
<td>
<% foreach (var ts in task.TimeSegments)
{ %>
<%= Html.TextBox("Hours", ts.Hours)%>
<% } %>
</td>
</tr>
<% } %>
</table>
<p>
<input type="submit" value="Spara tid" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
And I tried update it as usual just calling UpdataModel on the model object: UpdateModel(week); But that didn't work. So I read something about having to update each property separately in complex models, and tried to adapt it to my situation. Here's my attempt in the Controller:
[HttpPost]
public ActionResult EditTasks(int id, FormCollection collection)
{
//try
//{
Week week = _model.GetWeek(id);
foreach (var task in week.Tasks)
{
foreach (var timeSegment in task.TimeSegments)
{
UpdateModel(timeSegment.Hours, "Hours");
}
}
//UpdateModel(week);
_model.Save();
return RedirectToAction("Index");
//}
//catch
//{
// return View();
//}
}
But that didn't work either. It seems to work if the property is a string, but this is an int, and the compiler complains that it must be a reference type to be used as a TModel.
I don't know if this is the way to go, I just need to understand how to be able to update a complex type model like this. This can't be too uncommon so there must be some standard method, but I can't figure it out...
Any ideas?
UPDATE:
The following works:
Action method:
[HttpPost]
public ActionResult EditTasks(int id, FormCollection collection)
{
try
{
Week week = _model.GetWeek(id);
for (int i = 0; i < week.TaskList.Count; i++)
{
var task = week.TaskList[i];
for (int j = 0; j < task.TimeSegmentList.Count; j++)
{
int hours = Int32.Parse(collection["TaskList[" + i + "].TimeSegmentList[" + j + "].Hours"]);
week.TaskList[i].TimeSegmentList[j].Hours = hours;
}
}
//UpdateModel(week);
_model.Save();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
View:
<% for (int i = 0; i < Model.TaskList.Count; i++)
{
var task = Model.TaskList[i];
%>
<tr>
<td>
<%: task.Customer.CustomerName %>
</td>
<td>
<%: task.TaskName %>
</td>
<% for (int j = 0; j < task.TimeSegmentList.Count; j++)
{ %>
<td>
<%: Html.TextBoxFor(model => model.TaskList[i].TimeSegmentList[j].Hours, new { #class = "hourInput" })%>
</td>
<% } %>
</tr>
<% } %>
However, the updating has to be manual like this, which seems unnecessarily complex. I found a post by Phil Haack (http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx) which seems to suggest this should be possible to do in a simpler way, like this:
[HttpPost]
public ActionResult EditTasks(Week week)
{
try
{
UpdateModel(week);
_model.Save();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I.e. simply receiving the Week as the parameter for the method (in Haacks example it doesn't even seem he has to call UpdateModel, just having the View bound to the objects seems to be enough, so I would only have to save it in the database... But it doesn't work for me. The Week object that is returned doesn't seem to be the same one sent to the view, it has no items in its collections of tasks, e.g.
So why doesn't this work?
Try with for instead of foreach
<fieldset>
<legend>Fields</legend>
<table width="100%">
<% for (int i = 0; i < Model.Tasks.Count; i++)
{
var task = Model.Tasks[i];
%>
<tr>
<td>
<%: task.Customer.CustomerName %>
</td>
<td>
<%: task.TaskName %>
</td>
<td>
<% for (int j = 0; j < task.TimeSegments.Count; j++)
{ %>
<%= Html.TextBox("Model.Tasks["+i+"].TimeSegments["+j+"].Hours")%>
<% } %>
</td>
</tr>
<% } %>
</table>
<p>
<input type="submit" value="Spara tid" />
</p>
</fieldset>
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.