Get value from script to var in mvc - asp.net-mvc

I Have This Script:
<script language="JavaScript" src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
&&
<script type="text/javascript">
geoplugin_countryName();
geoplugin_countryCode();
</script>
this fun
#{
var current = Model.Where(f => f.CurrentRegion == "CurrentRegion" );
}
How can i make (CurrentRegion) = geoplugin_countryCode();
Note that the other does not work outside the script
#ViewBag.CurrentRegion = geoplugin_countryCode(); ///// Does not bring value
The name of this great website in value in the meaning of the need to ask for help

It does not work that way because the c# code in your view gets executed in the server while your javascript executes in the client side.
What you can do is keep 2 pages, In page1, execute your javascript and get the country code from your javascript function, then use that as a querystring param to naivgate to second page(Action method) where you will accept this country code in a parameter and do whatever you want.
So in your first page(view),
<script language="JavaScript" src="http://www.geoplugin.net/javascript.gp"
type="text/javascript"></script>
<script>
var countryCode = geoplugin_countryCode();
window.location.href="#Url.Action("SecondPage","YourControllerName")?country=" +
countryCode'
</script>
and the SecondPage action method
public ActionResult SecondPage(string country)
{
// use country to populate your view model
// to do : return something
}

You would need to POST this information back to the controller or make an AJAX request to a local web service that would know how to process the information.
Using JavaScript you can store the information in hidden input fields on the page and then POST that information back with page data you are submitting normally.

Related

Directive for loading forms into a single page app lost controller binding

I'm creating a single page app using AngularJS. I have created a main page with a custom directive for loading a form URL. I want to change the the forms based on a variable in my controller. However, I lost my bindings once I compiled and linked the form from URL
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app="tradesman" ng-controller="application" class="form-horizontal" role="form">
Hello {{applicant.name}}
<my-form name="formName">
</my-form>
</div>
var tradesman = angular.module("tradesman")
tradesman.controller("application",function application($scope){
$scope.formName="personals";
$scope.applicant={};
});
tradesman.directive("myForm",function($http,$compile){
return {
restrict:"E",
scope:false,
replace:true,
link:function(scope,element,attrs){
var url="http://tradesman.local/views/"+scope.formName+".html";
$http.get(url).then(function(response){
scope.$watch(function(){
element.html(response.data);
$compile(element.contents())(scope);
});
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
This has successfully loaded my personals page but lost the binding in that page. More over I want a new form to be loaded whenever I change my formName in controller.
What needs to be done to make form loading and binding work simultaneously

How do I use a Button(Non Submit) Click Event to call a method on my Controller?

I feel ridiculous asking this question but here goes, I am trying to make a very simple ASP.NET MVC 5 app. My first of it's kind. I want to have a button that when clicked does something but doesn't change the user's view or at most returns a "Email has been submitted" message.
My problem is I can't figure out how to wire a button to an "event" or "action" that doesn't change the view(i.e. using #Html.ActionLink()) or is a Submit button. Every example I find is also of a Submit button.
Thanks for any help.
EDIT
This is still not working for me. I'll post my code below. My effort is based on what was said here and on the linked post. Also, FYI, I can make it work with `#Html.ActionLink("link text", "actionname") but that appears as a link and I am trying to use a "Button".
Index.cshtml
#{
ViewBag.Title = "Home Page";
}
<div class="hero-unit">
<h3>Marketing & Communications Project Request Form</h3>
<p>User: <strong>#Context.User.Identity.Name</strong></p>
</div>
<div class="row">
<div class="span4">
#Html.ActionLink("Send Email", "SendEmail") #*this line works*#
<input id="SendEmail" class="btn" type="button" value="SendEmail" /> #*this line does not
</div>
</div>
<script type="text\javascript">
$(function(){
var url = '#Url.Action("SendEmail", "HomeController")';
$("input#SendEmail").on('click', function() {
$.ajax({
url: url
})
});
});
</script>
HomeController
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult SendEmail()
{
//Code to create and send email here
return View("Index");
}
}
OK, say you have the following button, written in HTML:
<input type="button" id="MyButton" value="Click Me />
You can use jQuery to hook up to the click event:
$(function(){
$("input#MyButton").on('click', function(){
// Do what you want.
});
});
If you use a HTML helper, such as HTML.TextBoxFor(), as long as you know the id of the input that is generated, you can use the same jQuery code to hook up the click event.
EDIT:
You can place that jQuery code either in the view e.g.
<script type="text/javascript">
$(function(){
$("input#MyButton").on('click', function(){
// Do what you want.
});
});
</script>
Usually you find script code placed near the bottom of the view, but you can place it anywhere you like really.
Or you could place that jQuery in a separate JavaScript (*.js) file. Just make sure you add the following to the <head> section in _Layout.cshtml:
<script type='text/javascript' src='#Url.Content("~Scripts/YourFile.js")' ></script>
_Layout.cshtml is a master layout file that is used across your project (assuming you have picked one of the usual ASP.NET MVC project templates in Visual Studio).
EDIT:
Regards the jQuery reference, in _Layout.cshtml you can add this, if jQuery is not already referenced:
<script type='text/javascript' src='#Url.Content("~Scripts/jquery.version.js")' ></script>
Just replace the filename for the correct one you have. Now, things get interesting if your MVC app uses bundling. That's a bit out of my knowledge bank, so might be better to look at other SO questions that talk about CSS/JavaScript bundling in MVC apps.
You could simply achieve with this below sample code using jQuery ajax(post) call
<a id="btn-send-mail">SendEmail</a>
JS
$(document).ready(function(){
$('#btn-send-mail').click(function(e){
e.preventDefault();
var emailData={};
emailData.toMail='sample#testmail.com';
$.post('/Mail/Send/',{data:emailData}, function(result){
if(result.status==true){
alert('Email submitted successfully');
}});//end of post
});//end of click
});//end of ready
Controller code
public class MailController
{
[HttpPost]
public JsonResult Send(Email obj)
{
//Code for sending email
return Json(new {status=true});
}
}
If you don't want to use normal jquery call you can take advantage of Razor #Ajax.ActionLink.
You just set up the link like a normal Html.ActionLink and then create a controller action that sends your email, since this call is asynchronous it wont refresh the page.
#Ajax.ActionLink("Send Email", // <-- Text to display
"SendEmail", // <-- Action Method Name
new AjaxOptions
{
UpdateTargetId="", // <-- Used if you want to update up, DOM element ID to update
HttpMethod = "GET" // <-- HTTP method
})
I would recomend doing the jquery way but here is an example using Ajax.ActionLink

Getting Null value for HttpPostedFileBase with Asp.Net MVC using the latest Uploadifive

So I am trying to implement Uploadifive 1.0 with Asp.NET MVC. Using the debugger mode, I know that the upload action is successfully passed to the Controller and the Server variables are passed as well. However, the HttpPostedFileBase variable fileData is always null. I've looked everywhere on google and couldn't find an answer. I found out that the variable has to be called fileData. That doesn't help though.
Here's part of the view:
<form action="<%: Url.Action("SaveFiles", "File") %>" enctype="multipart/form-data">
<input type="file" name="file_upload" id="file_upload" />
</form>
<script type="text/javascript">
(function ($) {
$(document).ready(function () {
$('#file_upload').uploadifive({
'method': 'post',
'uploadScript': 'SaveFiles',
'formData': {'path' : 'documents'}
});
});
})(jQuery);
</script>
Here's the controller action:
[HttpPost]
public ActionResult SaveFiles(HttpPostedFileBase fileData)
{
string uploadFolder = Request.ServerVariables.Get("HTTP_X_PATH");
if(string.IsNullOrWhiteSpace(uploadFolder))
return Json(JsonMessageManager.GetFailureMessage("No upload folder was selected"));
if (fileData != null && fileData.ContentLength > 0)
{
var fileName = Path.GetFileName(fileData.FileName);
var path = Path.Combine(Server.MapPath("~/Content/" + uploadFolder), fileName);
fileData.SaveAs(path);
return Json(true);
}
return Json(false);
}
Any pointers or help would be greatly appreciated. I feel lost.
I had the exact same problem with Uploadifive so I posted on the Uploadify forums on an existing thread (probably yours). The author has since posted an update to the Uploadifive plugin which I downloaded and now this works fine for me. In fact, it works exactly like Uploadify used to including additional form data being available in "Request.Forms" and it no longer prepends the "X_" to the additional form data. I would recommend you try the new version and see how you go.
See the discussion here: http://www.uploadify.com/forum/#/discussion/8223/no-files-attached-to-request
The key is not naming your variable 'fileData,' but rather making sure that your controller and UploadiFive both think it has the same name. For example:
Javascript:
$(document).ready(function () {
$('#fileUploadDiv').uploadifive({
'uploadScript': '/File/Upload',
'fileObjName' : 'file'
});
});
C# Controller:
[HttpPost]
public PartialViewResult Upload(HttpPostedFileBase file)
{
var name = file.FileName;
var stream = file.InputStream;
// etc...
}
As long as fileObjName has the same name as the parameter in your C# controller, you should be fine. I tested it with various names, and the parameter came in null if the names didn't match, and it worked like a charm when they did match.
If the parameter still doesn't work, you should be able to access the data using this.Request.Files inside of your controller. It looks like that data comes through regardless of parameter names.

using SignalR with document onload instead of jquery onload

I have used the signalR chat app (as laid out in this tutorial http://sergiotapia.com/2011/09/signalr-with-mvc3-chat-app-build-asynchronous-real-time-persistant-connection-websites/) in a standalone test site and it all works great.
I'm now trying to incorporate it into my larger project.
Now unfortunately my larger project has a body onload function defined, so i don't use the standard jquery $(function () {}); syntax for executing stuff on page load. This hasn't been too much of an issue so far, most jquery plugins and scripts get executed in the function called by my body onload and its fine.
But for some reason, my signalR code just isn't executing.
Its the exact same code as laid out above, only its called on my body load.
The page loads, does a post to /signalr/negotiate (which returns the url and clientID)
In my sample app which works, it then does a continuous post to /signalr/connect
In my other app, it simply does a single get to the page im currently on.
Its not making the post to connect.
Is there a way to manually call this?
Here is the source of the page not working.
Please note that the reason im not referencing JQuery itself is because its loaded in my master page. JQuery is present.
<script src="/public/javascript/jquery.signalR.min.js">
<script src="/public/javascript/json2.js">
<script type="text/javascript" src="/signalr/hubs">
<div>
<input type="text" id="msg" />
<input type="button" id="broadcast" />
<ul id="messages"></ul>
</div>
<script type="text/javascript">
function ExecuteOnLoad() {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addMessage = function (message) {
$('#messages').append('<li>' + message + '</li>');
};
$("#broadcast").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
// Start the connection
$.connection.hub.start();
}
</script>
EDIT : here is the chat hub
public class Chat : SignalR.Hubs.Hub
{
public void Send(string message)
{
//Call the addMessage method on all clients.
Clients.addMessage(message);
}
}
DOUBLE EDIT : ok, i've made a standard html page in my mvc project and wired up the onload event again and everything works fine. the problem seems to be that polling doesn't seem to working when i call
$.connection.hub.start();
instead its doing a get to the current url and returning the page again in the get request.
The problem had nothing to do with the question I asked.
I thought it might have to do with the onload function, but it did not.
The problem was because my page had a reference to the Jquery.Validate plugin.
The version I was using was 1.7, I updated to 1.9 of the plugin and it worked fine.

How to move focus to first error field with MVC client validation?

I use MicrosoftMvcValidation.js for client side validation. Error messages show correct. However, my page is kind of long and when the error shows, it does not automatically scroll up to show the 1st error message or set focus to error field. How can I show a message beside button like "Error happens. Please correct your input", but without list of field errors; or automatically move focus to 1st error field?
Whenever you have validation error, client-side validation will add input-validation-error class to those input boxes that caused validation. For example, in MVC3 if you have unobtrusive validation enabled you will get additional javascript files added to your file, like
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
This means that you can use your own jQuery functions after these lines that would detect whether input-validation-error exists or not. This piece of code is something that I am using in my applications:
$(document).ready(function () {
$("form[action*='New/']").submit(function () {
var firstError = $(this).children(":first has('.input-validation-error')");
if (firstError != null) {
firstError.focus();
return false; // no form posting
}
});
});
Replace the form[action*='New/'] with your form action, e.g. form[action*='/MyController/MyRegistrationAction/'] (*= means find this text at any location).

Resources