Check user web3.eth.accounts[0] value inside asp.net mvc action - javascript

How can I make sure inside my MVC action that the passed parameter string address is currently equal to JS window.web3.eth.acccounts[0]?
public ActionResult myAction( string address)
{
if(address == // there should be check js window.web3.eth.acccounts[0])
{
// other code
}
}

You can send it as a parameter to your action like:
public ActionResult myAction(string address, string eth3Info)
{
if(address == eth3Info)
{
//do the work
}
}
but honestly this won't make much sense as both things are coming from client side and can be easily manipulated.
You should have some backend call to get the window.web3.eth.acccounts[0] information from source.

Related

Return JavaScript from Controller As Content or JavaScriptResult

What is the difference if I return some JavaScript from my MVC controller as either
Content
[HttpPost]
public ActionResult MyEndPoint([System.Web.Http.FromBody] string result)
{
string jsResponse = "<script>";
if(result == "SUCCESS")
{
jsResponse = "SubmitOrder();";
}
else
{
jsResponse = "alert('Problem processing your order, please try again')";
}
jsResponse += "</script>";
return Content(jsResponse);
}
JavaScriptResult
[HttpPost]
public ActionResult MyEndPoint([System.Web.Http.FromBody] string result)
{
string jsResponse = "<script>";
if(result == "SUCCESS")
{
jsResponse = "SubmitOrder();";
}
else
{
jsResponse = "alert('Problem processing your order, please try again')";
}
jsResponse += "</script>";
return JavaScript(jsResponse);
}
Also, are there any security precautions I need to be aware of when return JavaScript from a MVC controller method/call?
For one, a JavaScriptResult returns the response as application/javascript MIME type vs the default text/html that using Content() returns. Because of that, the JavaScriptResult won't do what it looks like you're attempting (executing the JS). The browser doesn't just execute anything sent to in in a response. Since Content() is actually sending HTML, the browser can render it, in this case executing the script in the script tag. I haven't seen JavaScriptResult used often, but where I have, it's usually used to serve scripts dynamically. For example:
Controller
public ActionResult SomeAction() {
...
return JavaScript("script content");
}
View
<script src="MyController/SomeAction">
Regarding security, you'll obviously want to avoid executing anything that's been passed in from the user, whether that be from the request body, query string, etc. I'd wager, however it being a bit of a design issue and you couple your front end and back end, so regardless, it's probably best to use sparingly.

In an action method, how can I bind post data to a dynamic object?

I want to do this:
public ActionResult SaveStuff(dynamic vm) {
StoreTheValue(vm.myvalue);
return Content("Saved :)");
}
This doesn't work, MVC doesn't seem to want to create a dynamic object with properties that correspond to the post data of the request.
Now I know that the whole point of properly defined view models is to create strongly typed data structures and have MVC bind data into them, but given that I'm posting data from javascript using ajax it's not strongly typed data anyway, so I don't see that I'm loosing any maintainability by doing this, and it will save me time and effort creating view model classes.
Can anyone help suggest how I can bind post data to a dynamic object, posssibly using a custom model binder?
One possible way to achieve this would be to use a custom model binder, assuming that you are posting Json to the action
public class DynamicBinder : IModelBinder
{
public object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
{
using( var streamReader = new StreamReader( controllerContext.HttpContext.Request.InputStream ) )
{
return JsonConvert.DeserializeObject< dynamic >( streamReader.ReadToEnd() );
}
}
}
then in your action you can tell it, to use the custom binder
public ActionResult SaveStuff([ModelBinder(typeof(DynamicBinder))]dynamic vm) {
StoreTheValue(vm.myvalue);
return Content("Saved :)");
}
then post your json as such :
{
"myvalue":{...}
}
dynamic type and ajax request that you do with javascript is not corresponding.
You always can create your strongly typed object properties on javascript side.
Anyway you can use FormCollection like this:
[HttpPost]
public ActionResult yourAction(FormCollection collection)
{
StoreTheValue(Convert.ToString(collection["myvalue"]));
return Content("Saved :)");
}
But I think it's better to think of a strongly typed way.

Custom action result return specific view in MVC C#

I have an MVC application which i am trying to give the user the opportunity to download a zip of files,but unsuccesfully.Let me explain further.
Inside my view(ImageViewer.cshtml) i have a div class with an on click event that when pressed i call the controller method(ImageViewerController.GetZipPhotos) which handles the download of the zip file.See below:
div class="text" onclick="GetZipPhotos()">Download</div>
and the Javascript that get called is this:
function GetZipPhotos() {
$.ajax({
url: '#Url.Action("GetZipPhotos", "ImageViewer",Request.Url.Scheme)',
type: 'POST',
contentType: 'application/zip',
error: function () {
alert('There was an error!'+result);
}
});
}
Now, inside my ImageViewerController i have the following method:
[HttpPost]
public ActionResult GetZipPhotos()
{
ZipResult newZipResult=new ZipResult(
Server.MapPath("~/File1.txt"),
Server.MapPath("~/File2.txt")
);
newZipResult.OutPutZipFileName = "PhotosZip.zip";
return newZipResult;
}
and the declaration of the ZipResult custom action is:
public class ZipResult:ActionResult
{
private IEnumerable<string> _filesToZip;
private string _outPutZipFileName="ZipFile.zip";
public ZipResult(params string[] filesToZip)
{
this._filesToZip = filesToZip;
}
public override void ExecuteResult(ControllerContext context)
{
using (ZipFile oneZipFile = new ZipFile()) {
oneZipFile.AddFiles(_filesToZip);
context.HttpContext.Response.ContentType = "application/zip";
context.HttpContext.Response.AppendHeader("content-disposition", "attachment; filename=" + _outPutZipFileName);
oneZipFile.Save(context.HttpContext.Response.OutputStream);
}
}
}
The problem is that the code ofcourse doesn't work because the name of the view that called the controller is different from the actual method(GetZipPhotos).The view's name is ImageViewer.cshtml and the controller's name is ImageViewerController.
As fas as i have understood, the MVC framework uses code conventions, so it expects the name of the method to be the same as the view.The problem is that my view and the method are diferrent so the response never gets to back to the view.
I thought of creating a new view that has basically nothing inside, just to call it from the method and return the zip file.If this could be a possible solution, how can i tell from the action result which view to send the response?
No need to use ajax for the file download. The browser will normally start the download and keep you on the same page. Also, no need for a custom action result, you can just use FileResult. Try something like this:
public FileResult GetZipPhotos()
{
var filesToZip = new List<string> { Server.MapPath("~/File1.txt"), Server.MapPath("~/File2.txt") };
var oneZipFile = new ZipFile();
oneZipFile.AddFiles(filesToZip);
return File(oneZipFile.ToByteArray(), "application/zip", "PhotosZip.zip");
}
Of course, you'll need to figure out this part oneZipFile.ToByteArray(), but the ZipFile class probably already has something like that.
Your ajax call is redirecting the response into nowhere.
I would do it like this:
use a hidden iframe, change its src to the desired path in your function and it should be prompting a file dialog.

How to send a value from client side to server side for server side processing

I am trying to send a value from the client side using javascript or JQuery, to the server (ideally to a method in my codebehind). I am using C# .net 4.0.
In my client side JQuery I have:
$.post("test.aspx/testMethod",
{
name: "Donald Duck",
city: "Duckburg"
}
);
In my server side (test.aspx.cs) method, I have
public void testMethod()
{
string name = Request.Form("name");
string city = Request.Form("city");
}
But with this I get a compilation error: "Non-invocable member 'System.Web.HttpRequest.Form' cannot be used like a method."
How can I rectify this? Or reach the same objective? Using the $.ajax({...}) is not an option as the value is needed by a non-static method.
There is a very simple answer to this. After searching for hours thru dozens of questions posted along the same lines and many people offering overly complicated ajax post back solutions, I came up with this. Basically a one liner. Hope it helps someone:
In your javascript you just call the method:
PageMethods.SomeMethod('test');
Your "SomeMethod" would be a code behind method like this:
[WebMethod]
public static string SomeMethod(string param1)
{
string result = "The test worked!";
return result;
}
Rules:
You have to identify your code behind method with a WebMethod attribute. It has to be static. And you have to register a script manager in your page as follows:
<asp:ScriptManager ID="MyScriptManager" runat="server" EnablePageMethods="true" />
Since I am working with an aspx webforms page to do some really simple javascript functions like retrieving / stashing geo location, I put it inside the Form element as required.
you can use like this - https://rvieiraweb.wordpress.com/2013/01/21/consuming-webservice-net-json-using-jquery/
try it :)
I dont know if Web Forms support this type of JSON request. I have tried long back but I have to add asmx file that time. Currently you have WCF, but if you don't want to change your webforms project and still want restful api, then merge MVC project for your restful task. You dont have to shift everything but it work together. Here it is explained how?
I don't know about latest version of Web Forms but before VS2012, you can't do ajax type call to page. As far as I know.
Please let me know if any further details needed.
Found Solution... (Hope someone finds it useful)
JAVA SCRIPT
function myFunction() {
var str= "fname=Henry&lname=Ford";
log("MyString=" + str);
}
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "Default.aspx", true); // Default.aspx being the page being posted to
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(message);
}
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
string code = HttpContext.Current.Request.Form["MyString"];
// code = "fname=Henry"
// For looping etc, see below
}
}
WHAT ELSE YOU CAN GET....
HttpContext.Current.Request.Form.Count // 2
HttpContext.Current.Request.Form.Keys.Count // 2
HttpContext.Current.Request.Form.AllKeys[0] // "MyString"
HttpContext.Current.Request.Form.Keys[0] // "MyString"
HttpContext.Current.Request.Form.AllKeys[1] // "lname"
HttpContext.Current.Request.Form.Keys[1] // "lname"
HttpContext.Current.Request.Form[0] // "fname=Henry"
HttpContext.Current.Request.Form[1] // "Ford"
Loop through keys...
foreach (string key in Request.Form.Keys)
{
DoSomething(Request.Form[key]);
}
The above code works in that it passes a value(s) from the client side javascript to the server side code-behind, but then unable to use the value because you lose it.
The following modification to the above code is required to use the value (essentially store it in a separate static class until needed).
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
// Reset staticValue
Class1.staticValue = "";
Class1.staticValue = HttpContext.Current.Request.Form["MyString"];
// Call Class1.staticValue anywhere else and you get expected answer= "fname=Henry"
}
}
STATIC CLASS (App_Code/Class1.cs) - another object to store value (otherwise the HttpContext object removes it from anything)
public class Class1
{
private static string myValue = "";
public Class1()
{
//
// TODO: Add constructor logic here
//
}
public static string staticValue
{
get
{
return myValue;
}
set
{
myValue = value;
}
}
}

Can JavaScript read HTTP Session object?

Is it possible to read the value of a dynamic variable like httpRequest.getSession("attr_name") from within a JavaScript?
(With Javascript, I assume that you mean client script in the browser.)
No, that is not possible. The contents of the Session object never leaves the server, so client script can't read Session data directly.
If you want to access it in the browser, you have to read the data out of the Session object and send it along in the response (for example in a hidden field), or provide a web service that reads data from the Session object and returns to the browser.
As I said in my comment, the only way would be some kind of Ajax call and request it from the server. I dont know what backend your using, here's how I would do it in Asp.net MVC and jQuery.
(If there are minor syntax errors, I apologize - not in front of a compiler)
public class HomeController : Controller
{
//abstract the session code away, don't let the evil javascript touch
//it directly. Ideally this would all be in a seperate logic class or something.
public string NameAttribute
{
get
{
return Session["attr_name"] as string ?? string.empty;
}
}
[HttpGet]
public string GetNameAttribute()
{
return NameAttribute;
}
public ActionResult Index()
{
return View();
}
}
<script>
$(function(){
$.get( 'home/GetNameAttribute', function( response ) {
var name = response; //don't forget error checking, ommited
});
});
</script>
Alternatively, you could always write down the values you need into hidden fields, and read them with normal javascript.

Categories

Resources