Unable to add HTML.BeginForm inside ASP.NET WebGrid - asp.net

I have the following code inside my asp.net MVC-4 razor view:-
gridcolumns.Add(new WebGridColumn()
{
CanSort = false,
Format =
(item) =>
{
var banner = item.Value as Sales.Models.DeleteAllRequest;
if (!banner.Approved)
{
return Html.ActionLink("Approve", "DeleteRequestDeleteAll", "Customer", new { customerid = banner.CustomerID, requestid = banner.ID },
new AjaxOptions
{
Confirm = "Are You sure You want to delete (" + banner.CustomerName.ToString() + ")",
OnSuccess = "deletionconfirmation",
OnFailure = "deletionerror"
});
}
return "";
}
});
The above code will add <a> link inside the ASP.NET web grid column. but since i am doing a Delete action so i should be sending Post request instead of Get request. so i am not sure how i can use Html.BeginForm instead of Html.ActionLink inside my above code?
Thanks

Related

Asp.net MVC Ajax Button to retrieve a single data

I want to retrieve the first record in my database when ever I click the Ajax button, right now whenever I click my button it returns a List of my Record, I just want to retrieve the first record then when I click it again, returns the second record, is that even possible?
Here is my Ajax button :
#Ajax.ActionLink(" ", "BtnNext", null#*new { count = count + 1}*#, new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "current"
}, new { #class = "Middle-next dim btn btn-large-dim", #id = "Link1"})
Here is the controller for the Ajax button :
public PartialViewResult BtnNext()
{
var model = db.Queues.OrderBy(x => x.QueueNumber);
return PartialView("_queuenumber", model);
}
Thankyou so much, newbie <<
Try this
var model = db.Queues.ToList().OrderBy(x => x.QueueNumber).Take(1);

Post data with free-jqgrid, what are the code in client and Web API side?

I am using ASP.NET MVC 6 Web API. In the View I use free-jqgrid.
Let's borrow Oleg's free jqgrid data to demonstrate my purpose. We already have the table shown.
Next I am going to add new Vendor. Please notify that there is primary key id(identity column) in the database. We don't want it displaying in the screen.
In VendorRespository.cs, I add the new Vendor as
public void AddVendor(Vendor item)
{
using (VendorDataContext dataContext = new VendorDataContext())
{
dataContext.Database.Connection.ConnectionString = DBUtility.GetSharedConnectionString(
"http://centralized.admin.test.com");
var newVendor = dataContext.Vendors.Create();
newVendor.Company = item.Company;
newVendor.ContactName = item.ContactName;
newVendor.ContactPhone = item.ContactName;
newVendor.UserName = item.UserName;
newVendor.UserKey = item.UserKey;
newVendor.Active = item.Active;
newVendor.FacilityId =item.FacilityId;
newVendor.ClientID = item.ClientID;
dataContext.SaveChanges();
}
}
My questions:
Not sure the script like?
<script>
API_URL = "/VendorManagement/";
function updateDialog(action) {
return {
url: API_URL
, closeAfterAdd: true
, closeAfterEdit: true
, afterShowForm: function (formId) { }
, modal: true
, onclickSubmit: function (params) {
var list = $("#jqgrid");
var selectedRow = list.getGridParam("selrow");
rowData = list.getRowData(selectedRow);
params.url += rowData.Id;
params.mtype = action;
}
, width: "300"
};
}
jQuery("#jqgrid").jqGrid('navGrid',
{ add: true, edit: true, del: true },
updateDialog('PUT'),
updateDialog('POST'),
updateDialog('DELETE')
);
In the controller, not sure what is the code?
// POST
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
My code has many compiling errors such as
'HttpRequest' does not contain a definition for 'CreateResponse' and the best extension method overload 'HttpRequestMessageExtensions.CreateResponse(HttpRequestMessage, HttpStatusCode, Vendor)' requires a receiver of type 'HttpRequestMessage'
Please help me to get rid of the error and inappropriate code.
EDIT:
I borrowed the code snippet from here.
I need add the code such as
[Microsoft.AspNet.Mvc.HttpGet]
public dynamic GetVendorById(int pkey)
{
return null;
}
And
// POST
[System.Web.Http.HttpPost]
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("/VendorManagement/GetVendorById", new { id = item.pkey });
response.Headers.Location = new Uri(uri);
return response;
}

Why my yui datatable within an updatepanel disappears after postback?

I got my YUI datatable rendered with my json datasource inside an updatepanel... If i click a button within that updatepanel causes postback and my yui datatable disappears
Why yui datatable within an updatepanel disappears after postback?
EDIT:
I am rendering YUI Datatable once again after each post back which is not a form submit... I know it is a bad practice...
What can be done for this.... Any suggestion.....
if (!IsPostBack)
{
GetEmployeeView();
}
public void GetEmployeeView()
{
DataTable dt = _employeeController.GetEmployeeView().Tables[0];
HfJsonString.Value = GetJSONString(dt);
Page.ClientScript.RegisterStartupScript(Page.GetType(), "json",
"EmployeeDatatable('" + HfJsonString.Value + "');", true);
}
When i click any button in that page it causes postback and i have to
regenerate YUI Datatable once again with the hiddenfield value containing
json string..
protected void LbCancel_Click(object sender, EventArgs e)
{
HfId.Value = "";
HfDesigId.Value = "";
ScriptManager.RegisterClientScriptBlock(LbCancel, typeof(LinkButton),
"cancel", "EmployeeDatatable('" + HfJsonString.Value + "');, true);
}
My javascript:
function EmployeeDatatable(HfJsonValue){
var myColumnDefs = [
{key:"Identity_No", label:"Id", width:50, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Emp_Name", label:"EmployeeName", width:150, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Address", label:"Address", width:200, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Desig_Name", label:"Category", width:200, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"", formatter:"checkbox"}
];
var jsonObj=eval('(' + HfJsonValue + ')');
var target = "datatable";
var hfId = "ctl00_ContentPlaceHolder1_HfId";
generateDatatable(target,jsonObj,myColumnDefs,hfId)
}
function generateDatatable(target,jsonObj,myColumnDefs,hfId){
var root;
for(key in jsonObj){
root = key; break;
}
var rootId = "id";
if(jsonObj[root].length>0){
for(key in jsonObj[root][0]){
rootId = key; break;
}
}
YAHOO.example.DynamicData = function() {
var myPaginator = new YAHOO.widget.Paginator({
rowsPerPage: 10,
template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
rowsPerPageOptions: [10,25,50,100],
pageLinks: 10 });
// DataSource instance
var myDataSource = new YAHOO.util.DataSource(jsonObj);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {resultsList: root,fields:new Array()};
myDataSource.responseSchema.fields[0]=rootId;
for(var i=0;i<myColumnDefs.length;i++){
myDataSource.responseSchema.fields[i+1] = myColumnDefs[i].key;
}
// DataTable configuration
var myConfigs = {
sortedBy : {key:myDataSource.responseSchema.fields[1], dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
paginator : myPaginator
};
// DataTable instance
var myDataTable = new YAHOO.widget.DataTable(target, myColumnDefs, myDataSource, myConfigs);
myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow);
myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
myDataTable.subscribe("checkboxClickEvent", function(oArgs){
var hidObj = document.getElementById(hfId);
var elCheckbox = oArgs.target;
var oRecord = this.getRecord(elCheckbox);
var id=oRecord.getData(rootId);
if(elCheckbox.checked){
if(hidObj.value == ""){
hidObj.value = id;
}
else{
hidObj.value += "," + id;
}
}
else{
hidObj.value = removeIdFromArray(""+hfId,id);
}
});
myPaginator.subscribe("changeRequest", function (){
if(document.getElementById(hfId).value != "")
{
if(document.getElementById("ConfirmationPanel").style.display=='block')
{
document.getElementById("ConfirmationPanel").style.display='none';
}
document.getElementById(hfId).value="";
}
return true;
});
myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
oPayload.totalRecords = oResponse.meta.totalRecords;
return oPayload;
}
return {
ds: myDataSource,
dt: myDataTable
};
}();
}
Hai guys,
I got an answer for my qusetion.... Its my postback that caused the problem and i solved it by making an ajax call using ajax enabled WCF Service in my web application... Everything works fine now....
Anything you are generating client side will have to be regenerated after every page refresh (and after every partial page refresh, if that part contains client-side generated html).
Because the YUI datatable gets its data on the client, you will have to render it again each time you replace that section of html.

ASP.Net MVC RedirectToAction with anchor

I have the following problem:
For example I have route like this:
routes.Add(new Route("forums/thread/{threadOid}/last", new MvcRouteHandler())
Defaults = new RouteValueDictionary(
new { controller = "Thread", action ="ShowThreadLastPostPage"}),
Constraints = new RouteValueDictionary(new { threadOid = #"^\d+$" })
}
);
Is there a way using RedirectToAction method navigate to the URL like this:
forums/thread/{threadOid}/last#postOid
I think you should use the Redirect method along with Url.RouteUrl to accomplish it.
return Redirect(Url.RouteUrl(new { controller = "Thread", action = "ShowThreadLastPostPage", threadOid = threadId }) + "#" + postOid);
Another alternative with Url.Action:
return Redirect(Url.Action("ShowThreadLastPostPage", "Thread", new { threadOid = threadOid }) + "last#" + postOid);

Are there caveats to dynamicly creating a form with javascript?

I have to do a cross site POST (with a redirection, so not using a XMLHTTPRequest), and the base platform is ASP.NET. I don't want to POST all of the controls in the ASP.NET FORM to this other site, so I was considering dynamicly creating a new form element using javascript and just posting that.
Has anyone tried this trick? Is there any caveats?
I do this all the time. Works really well. You will have to look through the Request's parameters manually, though, unless you get creative with what you pass as the parameters won't map onto controls on that page. You could also do this in a REST way by passing the parameters in the query string, but I prefer the forms approach to keep my URLs clean. Note that ASP.NET ignores all forms but it's own on postback so I don't bother removing them.
Example from a GridView template field for below code:
<asp:TemplateField HeaderText="Station" SortExpression="Name">
<ItemTemplate>
<a href="javascript:void(0);" onclick='Redirector.redirect_with_id("StationDetail.aspx", <%# Eval("StationID") != null ? Eval("StationID") : "-1" %>);return false;'>
<asp:Label ID="nameLabel" runat="server" Text='<%# Bind("Name") %>' /></a>
</ItemTemplate>
</asp:TemplateField>
Code below -- requires Prototype:
// JScript File
var Redirector = Class.create();
Redirector.prototype = {
initialize: function(url,target) {
this.url = url;
this.parameters = new Hash();
this.target = target;
},
addParameter: function(id,value) {
this.parameters.set(id, value);
},
redirect: function() {
var form = document.createElement('form');
document.body.appendChild(form);
form.action = this.url;
form.method = "post";
if (this.target) {
form.target = this.target;
}
this.parameters.each( function(pair) {
var input = document.createElement('input');
input.id = pair.key;
input.name = pair.key;
input.value = pair.value;
input.style.display = 'none';
form.appendChild(input);
});
form.submit();
}
};
Redirector.redirect_with_id = function(url,id,target) {
var redirector = new Redirector( url, target );
redirector.addParameter( 'ID', id );
redirector.redirect();
};
Redirector.redirect_with_tag = function(url,tag_name,tag,target) {
var redirector = new Redirector( url, target );
redirector.addParameter( tag_name, tag );
redirector.redirect();
};
Redirector.redirect_with_tags = function(url,tag_names_comma_separated,tag_values_comma_separated,target) {
var redirector = new Redirector( url, target );
var tags = tag_names_comma_separated.split( "," );
var values = tag_values_comma_separated.split( ",");
for( var i = 0; i< tags.length; i++ )
{
redirector.addParameter( tags[i], values[i] );
}
redirector.redirect();
};
One caveat: you cannot add a FORM tag to the document using innerHTML. You must add it by creating a new DOM element. You can add fields using innerHTML, but not the form itself.

Resources