|
No, not out of the box. The closest way to return nothing from an ActionResult returning method is the aforementioned EmptyResult.
That said, there is a way to do something similar by adding a route and a void method.
RouteConfig.cs
...
routes.MapRoute(
"DetailOverload",
"Department/Details",
new { controller = "Department", action = "VoidDetails" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
DepartmentController.cs
public void VoidDetails()
{
}
public ActionResult Details(int id)
{
}
This is basically the .NET MVC baked-in way to modify action calls.
|
|
|
|
|
Ah, so it is possible by putting it into the route config file and pointing it to a void controller function. Why didn't they write this to be something intuitive, like returning NULL to the view engine? Instead, you have to modify routing to catch a hacked path in order to have the server not return anything to the browser.
In the end, I guess it would be simpler to check for hacked paths and redirect to the site homepage if found. Is there any pseudo-standard handling of responses to hacked paths?
if (Object.DividedByZero == true) { Universe.Implode(); }
|
|
|
|
|
Well, the fact is this behavior breaks the expected functionality of HTTP; the appropriate response by convention would be to return an HttpNotFound() if the id is not set or null, or send down a view with a list of possible values.
Generally the expected behavior for HTTP is to send a request and get a response of some sort. Black-holing the response is just not the norm.
All that said, I wasn't in on the meetings where they defined the standards that were going into MVC (it'd hopefully be less cluttered if I was )
And to answer your question, you're overthinking that. I went back and re-read your initial post and have a much better solution for you:
DepartmentController.cs
{
public ActionResult Details(int? id)
{
if(id == null)
{
return View("Home");
}
}
}
No new routes or anything needed.
|
|
|
|
|
Nathan Minier wrote: Well, the fact is this behavior breaks the expected functionality of HTTP; the appropriate response by convention would be to return an HttpNotFound() if the id is not set or null, or send down a view with a list of possible values.
Generally the expected behavior for HTTP is to send a request and get a response of some sort. Black-holing the response is just not the norm.
I was kinda expecting this.
It explains why the other answers were all along the lines of 'Just redirect to X.' Thank you for taking the time to explain that it is possible and how it can be done but also why it is not recommended. I learned something new today.
Thanks.
if (Object.DividedByZero == true) { Universe.Implode(); }
|
|
|
|
|
in the aspx form contain 1 text box and search button.
when enter some text in text box and click search button.
when we click the button then open a pdf file and hilight the text that are given in the text box with background colour
|
|
|
|
|
Hi All,
I am using ORM tool NetTiers for my Web Application, I don't know the reason but my NetTiers setting weren't saved in the .cst file and I missed the .csp file, I don't know which file saves all my settings.
When VM was restarted all the settings are lost now when I am trying to generate the code again using Nettiers, it is creating the Delete methods twice and giving me error.
Can anybody please help me which settings I should make in NetTiers to not to do it and to save those changes in some where?
Any help is much appreciated buddies, a code snippet, a link or even suggestion.
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
Hello All -
I'm trying to find best technique to handle the situation where my web page (.aspx) stay active ( able to edit and click items on it) while part of the screen showing a update bar indicating that asynchronous function is still active. When that task gets over server sends the message out to page with link to a .txt file ready to download.
I read up on Async/Wait; And it can start the Asyn task but I could not figure out how to send the message out to client upon tasks completion.
I'm open to any technique that works not married to async/await. I code in VB. Any pointer/suggestions/links are appreciated!!
Thank you!!
Ajay Sharma
|
|
|
|
|
I have a form with 3 related dropdownlist and a text input.
That means the first dropdownlist filter the second dropdownlist calling an webapi, the second dropdownlist filter the next dropdownlist calling another webapi.
At document.ready, I fill the dropdownlists with default options.
Of course, I map the dropdownlist's on change event to fill according the parente dropdownlist selection.
Now, if the user fill a code into text input, all dropdownlists must be updated, according the input code.
The first dropdownlist is working fine, but none of the other two are filled.
Can someone show me some example about how to do it?
Thank you.
Luís Oliveira
|
|
|
|
|
Thank you in advance for any help!
I have a GridView on an aspx page with two criteria: From Date and To Date (both text boxes). There also is a Search button.
The GridView is bound to a SQL Data Source and the two text boxes are the two criteria for a stored procedure. There is no code-behind.
If I enter both From and To dates and click the Search button, the grid appears and clicking on a sortable column header resorts the grid.
If I enter neither dates and click the Search button, the grid appears. However, when I click a sortable column header, the grid disappears. If I click the Search button again, the grid reappears - and is sorted properly.
Can someone tell me why that occurs?
|
|
|
|
|
Have you set the SqlDataSource 's CancelSelectOnNullParameter property[^] to false ?
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Yes. That criterion is set to False in the code behind.
No. It was not set on the .aspx page. I added it to the dataset source and it worked!
Thank you!
|
|
|
|
|
Without using microsoft appid and just like a program.
|
|
|
|
|
|
I write a custom server control with javascript
the javascript is as the following and is tested , which can use "Enter" key to go to the next textbox
------ test0205.html ------------------
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(':input').keydown(function(e){
if (e.keyCode == 13 ){
$(':input').eq($(':input').index($(this)) + 1).trigger('focus');
}
});
});
</script>
</head>
<body>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
</body>
</html>
--------------------------------------------------------------------
But after I put it into my server contro project (ServerControl6)
and use the control in the web page (Default4.aspx) , the code as follows
-------------------- ServerControl6.cs -------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ServerControl6
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl6 runat=server></{0}:ServerControl6>")]
public class ServerControl6 : System.Web.UI.WebControls.TextBox
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null)? "[" + this.ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string scriptKey = "TextBoxEnter" + this.UniqueID;
ClientScriptManager cs = Page.ClientScript;
Type cstype = this.GetType();
if (!cs.IsClientScriptBlockRegistered(scriptKey))
{
string scriptBlock =
@"<script language=""JavaScript"">
<!--
$(document).ready(function(){
$(':input').keydown(function(e){
if (e.keyCode == 13 ){
$(':input').eq($(':input').index($(this)) + 1).trigger('focus');
}
});
});
// -->
</script>";
cs.RegisterClientScriptBlock(cstype, scriptKey, scriptBlock);
}
}
}
}
-------------------- AssemblyInfo.cs -----------------------
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Web.UI;
[assembly: AssemblyTitle("ServerControl6")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServerControl6")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("02a2c0e8-68f5-4df3-b8c2-97f433584357")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TagPrefix("ServerControl6", "aspSample")]
-------- Default4.aspx ------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<%@ Register assembly="ServerControl6" namespace="ServerControl6" tagprefix="aspSample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style type="text/css">
#form1 {
height: 579px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 525px">
<br />
<aspSample:ServerControl6 ID="ServerControl61" runat="server"></aspSample:ServerControl6>
<br />
<br />
<aspSample:ServerControl6 ID="ServerControl62" runat="server"></aspSample:ServerControl6>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
---------------------------------------------------------------------
I tried to save the html code generated by asp.net as a html file(render2016-1.html) which is the following
---------------- render2016-1.html ------------------
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>
</title>
#form1 {
height: 579px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<form method="post" action="Default4.aspx" id="form1">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="CoCWzO/vWYkNRBCpFbIQ3IPvm7ueZdcg7gaDU3S4YPnnHh6YhLHAUgVDIaTSe9kaEwNqnlScnHq/YYOhf5gw+s7Wu6bUynanqupEJH8WIzNkDwKd6PYNgPGXNfkR6Mgk" />
<script language="JavaScript">
</script><script language="JavaScript">
</script>
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="44C02278" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="U2n4TbuH4IvEG/Bsq9RE7wS5fX5d/+Qb6Mh7sWlT0q4BldcSVq6R7yngmv2WKGXiMAOpblFJWUaqnXayL+azyfmb/UwOyyH57eegvf6lOVxY9j4GXrBoz8wSRk82espsW3DJ0rCLi48RAmK9xboMgunbb+oWfe6ScP1QWMsabqU=" />
<input name="ServerControl61" type="text" value="123" id="ServerControl61" />
<input name="ServerControl62" type="text" id="ServerControl62" />
<input type="submit" name="Button1" value="Button" id="Button1" />
</form>
</body>
</html>
---------------------------------------------------------------------
while I use the browser debug tool to run the code , there is a error message as below
---------------------------------------------------------------------
This page contains the following errors:
error on line 1 at column 2: StartTag: invalid element name
Below is a rendering of the page up to the first error.
---------------------------------------------------------------------
Is there anybody can tell me where is the problem ?
|
|
|
|
|
You should format the post, it is next to impossible to read it!
1. Remove all unnecessary lines (at least the blanks)
2. Format the code blocks
3. Add inline comments to show where the error is (we can't see your line numbers!)
Skipper: We'll fix it.
Alex: Fix it? How you gonna fix this?
Skipper: Grit, spit and a whole lotta duct tape.
|
|
|
|
|
Hi, I am able to select any item in the List and save it Properly, but when I load the page again, what I want is User should be able to see previously selected item as selected rather than selected nothing. For that, it is happening when I select the parent level item but not happening if the selected item is Child.
I am using the below code to retrieve the selected item, as TaxanomyChildIdSelected value would be coming from database and depending upon that value I want to show the user which item has has selected Previously. I am using below code to do that. But FindItemByKeyValue function returns null when I am trying to retrieve the Child level item. Any help a code snippet, link or even suggestion would be very very helpful. Thanks in advance.
TreeListDataItem item = rtlManageHealthTopics.FindItemByKeyValue("HealthTopicId", TaxanomyChildIdSelected.ToString());
if ((item != null) && !DBNull.Value.Equals(item))
item.Selected = true;
Below is the full code
WebAdmTopicHealthTopicService _objWebAdmTopicHealthTopicService = new WebAdmTopicHealthTopicService();
var _listOfWebAdmTopicHealthTopic = _objWebAdmTopicHealthTopicService.Find(" TopicId= " + _topic.TopicId.ToString());
if((_listOfWebAdmTopicHealthTopic!=null) && !DBNull.Value.Equals(_listOfWebAdmTopicHealthTopic) && (_listOfWebAdmTopicHealthTopic.Count>=1))
{
WebAdmHealthTopicViewService _objWebAdmHealthTopicViewService = new WebAdmHealthTopicViewService();
var _listOf_objWebAdmHealthTopicView = _objWebAdmHealthTopicViewService.Get(" HealthTopicId = " + _listOfWebAdmTopicHealthTopic[0].HealthTopicId.ToString() , " Name ");
if ((_listOf_objWebAdmHealthTopicView != null) && !DBNull.Value.Equals(_listOf_objWebAdmHealthTopicView) && (_listOf_objWebAdmHealthTopicView.Count() >= 1)
&& (_listOf_objWebAdmHealthTopicView != null) && (_listOf_objWebAdmHealthTopicView[0].HealthTopicId > 0))
{
var _objOf_objWebAdmHealthTopicView = _listOf_objWebAdmHealthTopicView[0];
TaxanomyChildIdSelected = _listOfWebAdmTopicHealthTopic[0].HealthTopicId;
TreeListDataItem item = rtlManageHealthTopics.FindItemByKeyValue("HealthTopicId", TaxanomyChildIdSelected.ToString());
if ((item != null) && !DBNull.Value.Equals(item))
item.Selected = true;
}
}
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
I didn't want to use the Owin security, yet wanted to use a custom Attribute [Security] for my Controller action results to validate the user before doing anything. Currently I'm using Sessions to store the Name.
But when I run the Attribute, the System.Web.HttpContext.Current.User Name is empty.
I'm not sure if I implemented the construction of the System.Web.HttpContext.Current.User wrong, of if the value won't persist because I placed in another class. Or perhaps I'm suppose to store something in the database for this.
This is everything I have. I call the code below on a successful login.
String[] newRoles = { "Administrator", "Customer" };
GenericIdentity newIdentity = new GenericIdentity(model.AccountName);
GenericPrincipal newPrincipal = new GenericPrincipal(newIdentity, newRoles);
System.Web.HttpContext.Current.User = newPrincipal;
My custom Attribute, that I wrote in another class Dll.
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class SecurityCheckAttribute : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string accountName = HttpContext.Current.User.Identity.Name;
if (accountName != null)
{
bool result = ef_website_accounts.verify_accountName(accountName);
if (false == result)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary{
{ "controller", "Admin" },
{ "action", "Logout" }
});
}
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary{
{ "controller", "Admin" },
{ "action", "Logout" }
});
}
base.OnActionExecuting(filterContext);
}
}
I'd rather build a mini Owin in where I can store user information in an object and call it anywhere on the back end, but this is a start.
The one that came with the program was too complex for my needs, And if it keeps changing, I didn't want to deal with more code updates.
|
|
|
|
|
After reading for hours on the subject, I found that System.Web.HttpContext.Current only has a life span of 1 request and then it dies. So in theory, if I use HttpContext.Current.User, then that should only have a life span of 1 request.
Then there was System.Threading.Thread.Principal. But my research says that you cannot control which thread in the IIS Thread pool will service the request. You have to make a thread, and the life span will be the life of the thread.
So I'm back to the Session, but used in my attribute which does work at the moment.
I'll think about how to make something in my security DLL persist for the user in there session. I wonder how Owin does it.
|
|
|
|
|
Not sure about OWIN, but traditionally in ASP.NET, you would handle the HttpApplication.AuthenticateRequest event[^] to check whether the user has already authenticated and set up the HttpContext.User for the current request. I'd assume there's something similar in OWIN.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
You got the wheels turning in my head. I didn't know about that.
My last post created an issue with the AntiForgeryToken, in which the token identified me or was looking for me, but got nothing. The opposite of all the search results I found.
And I looked at Angular.js, but my research concluded that I had to dump JQuery and go Angular.
So I'm not ready for that yet.
|
|
|
|
|
Hi,
I am trying to validate below input type using custom validator and client side validation. If I am using the Javascript code in the asp .net page ..its working fine. But if I am using same code in separate JavaScript file it is not working. I need help
Thank You
.....................................................
Javascript code:
function FirstNameValidate(sender, args) {
//do your validation logic
if (document.getElementById("txtFirstName").value == '')
args.IsValid = false;
if (!args.IsValid)
var ctrl = $("#" + sender.controltovalidate);
if (ctrl) {
ctrl.css({ "border": "1px solid red" });
sender.innerHTML = "Please enter First Name.";
}
}
...................................
<asp:customvalidator id="firstNameValidator" runat="server" errormessage="" display="Dynamic"
controltovalidate="txtFirstName" forecolor="red" validationgroup="registerButton"
onservervalidate="firstNameValidator_ServerValidate" validateemptytext="True"
clientvalidationfunction="FirstNameValidate" setfocusonerror="true">
<asp:textbox id="txtFirstName" class="form-control" placeholder="First name" runat="server">
|
|
|
|
|
Ok so you're showing us the working version rather than the broken one?
Are you sure you're including your external JS file in the page? Are any errors thrown up by the browser?
|
|
|
|
|
Yes ..this is the working version..
|
|
|
|
|
Right but we need the not working version otherwise how can anyone see what's wrong?
Additionally, did you check my other point?
|
|
|
|
|
I would highly recommend not hard coding the text box id in your JavaScript custom validation function. It limits its reuse. Everything you need can be retrieved from sender and args.
|
|
|
|