Adding Parameters to URL.Action in Razor - c#

Hi all Currently I have a website that has a button and some javascript that creates a loading look and then runs this actionresult. I want to add parameters to actionresult but not sure how to do it. Thanks! Here is my code
Controller:
[HttpPost]
public ActionResult PostMethod(string MyText)
{
System.Threading.Thread.Sleep(5000);
return Json("And were done");
}
View:
<input type="text" name="MyTextBlock"/>
<p id="PID">
Default message from declarative syntax.
</p>
<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px;
top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001;
opacity: .8; filter: alpha(opacity=70);display:none" >
<p style="position: absolute; top: 30%; left: 45%; color: White;" align="center">
<img src="../../Content/themes/base/images/ajax-loading.gif"><br />
Loading, please wait...
</p>
</div>
<button onclick="JavascriptFunction();">HTTPPost Button</button>
<script type="text/javascript" language="javascript">
function JavascriptFunction() {
var url = '#Url.Action("PostMethod", "MyTextBlock", new { MyText = "john" })';
$("#divLoading").show();
$.post(url, null,
function (data) {
$("#PID")[0].innerHTML = data;
$("#divLoading").hide();
});
}
</script>
What I want to do is pass MyTextBox into PostMethod to use it as MyText. Some of the other examples I have seen hardcode in values where I want it to be from the textbox. Any help is greatly appreciated. Thanks!

Razor is generated before page load, so if you want a textbox after the page is loaded you need to use javascript (that is to say if the end-user will be changing the value of MyTextBox and you want to pass this new value using AJAX).
Instead of passing null as your data argument in $.post, this is where you would grab the value of MyTextBox and pass it to the action. For example:
var url = '#Url.Action("PostMethod")';
var data = $('input[name="MyTextBox"]').serialize();
$.post(url, data, function(data){
});

It seems like you're trying to hand code a lot of what MVC already handles for you. Try this out...
First out, create a model for your view. You can call this whatever you want. Put the properties that you want as your parameters to your action method in here.
YourModel.cs
public class YourModel
{
public string MyText { get;set; }
}
For your controller, you'll have to change two things. The GET action for the page will need a model passed to it, like shown below.
For the POST action, change your string MyText parameter to YourModel model. This will allow MVC to bind your inputs on your view to the model.
Action Method
public class YourController
{
[HttpGet]
public ActionResult PostMethod()
{
YourModel model = new YourModel();
return View(model);
}
[HttpPost]
public ActionResult PostMethod(YourModel model)
{
//Do something with model.MyText;
System.Threading.Thread.Sleep(5000);
return Json("And We're Done");
}
}
PostMethod.cshtml
//THIS LINE HERE IS THE MOST IMPORTANT
#model YourNamespace.YourModel
//Ajax will handle most of the calling and showing of your elements if you tell it what to do!
#using(Ajax.BeginForm(new AjaxOptions(){ LoadingElementId="divloading", OnSuccess="OnSuccessFunction" }))
{
<input type="text" name="MyText"/>
//Quick note: If you decide to hand code your html, make sure your <input/> name attributes match the property names on your model object.
//Or here you could do #Html.TextBoxFor(m => m.MyText)
<p id="PID">
Default message from declarative syntax.
</p>
<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px;
top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001;
opacity: .8; filter: alpha(opacity=70);display:none" >
<p style="position: absolute; top: 30%; left: 45%; color: White;" align="center">
<img src="../../Content/themes/base/images/ajax-loading.gif"><br />
Loading, please wait...
</p>
</div>
<input type="submit" name="Submit" value="HTTPPost Button"/>
<script type="text/javascript" language="javascript">
function OnSuccessFunction(data, textStatus, jqXHR){
$("#PID")[0].innerHtml = data;
}
</script>
}
Some benefits of doing it this way is now your JS doesn't have to change if you add more properties to your model. You just add another input to your view using either the HtmlHelper or hand code the input name with the name attribute equal to the name of the property on your model. MVC will handle the rest.

Related

How Send text to textarea in webbrowser C#

This is the textarea. I want to send value there but. There isnt name or id. I couldnt send value.
<div id="cke_1_contents" class="cke_contents cke_reset" role="presentation" style="height: 300px;">
<textarea style="width: 100%; height: 100%; resize: none; outline: currentcolor none medium; text-align: left; -moz-tab-size: 4;" dir="ltr" class="cke_source cke_reset cke_enable_context_menu cke_editable cke_editable_themed cke_contents_rtl" tabindex="0" role="textbox" aria-multiline="true" aria-label="ویرایش‌گر متن غنی, txtPostContent" title="ویرایش‌گر متن غنی, txtPostContent"></textarea>
</div>
you can set the value of textarea inside the WebBrowser component by executing the below code
//get the main div HTML element by ID
var cke1ContentsElements = webBrowser1.Document.GetElementById("cke_1_contents");
//from main div select all HTML elements with the tag name "textarea"
var cke1TextareaList = cke1ContentsElements.GetElementsByTagName("textarea");
//from the selected list of items set value attribute for first element
cke1TextareaList[0].SetAttribute("value", "Send This String To TextArea ");

Inconsistent error message DOM betweeen jQuery validation and Postback

My error message html structure from jQuery validation and from postbacks are different causing my validation errors to display differently. I need the nested span tag within the span.field-validation-error because I use CSS to add the (x) icon before the message like the one you see on the Description error message.
This is the error message from jQuery validation.
<span class="field-validation-error" data-valmsg-for="Code" data-valmsg-replace="true">
<span id="Code-error" class="">The Description field is required.</span>
</span>
notice that on the banner url validation message, there's no span tag within the span.field-validation-error.
<span class="field-validation-error" data-valmsg-for="BannerUrl" data-valmsg-replace="true">
The Banner Image field is required.
</span>
This is the view cshtml file markup I have.
<div class="form-group">
#Html.LabelFor(x => x.Description):
#Html.TextAreaFor(x => x.Description, new { rows = 5, cols = 5, #class = "form-control", placeholder = "Enter your team description" })
#Html.ValidationMessageFor(x => x.Description)
</div>
<div class="form-group">
#Html.LabelFor(x => x.BannerUrl):
<input id="BannerUrl" name="BannerUrl" type="file" class="file-styled">
#Html.ValidationMessageFor(x => x.BannerUrl)
</div>
Why does the error message html from jquery validation different from the error message html that's generated after postback?
EDIT:
Below is the CSS that adds the (X) icon before the error message. What I really want it to do is for the icon to show up in front of the error message that comes from a postback (no nested span) and also the error message from jquery validation (nested span).
.field-validation-error > span:before {
font-family: 'icomoon';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
min-width: 1em;
display: inline-block;
text-align: center;
font-size: 16px;
vertical-align: middle;
position: relative;
top: -1px;
/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
content: "\ed63";
margin-right: 5px;
}
The jquery.validate.js plugin and the MVC framework are developed by separate teams (jquery.validate is not associated with Microsoft). The MVC framework just uses jquery.validate.js for client side validation (and use jquery.validate.unobtrusive.js to add the rules to jquery.validate.js).
You could create you own HtmlHelper extension to generate the inner <span> element server side. For example, copy the ValidationExtensions.cs source code and modify the private static MvcHtmlString ValidationMessageHelper(...) method so that instead of builder.SetInnerText(validationMessage); you use builder.InnerHtml = xx; where xx is a TagBuilder that builds a <span> containing the error message.
However, it would be easier to just use some javascript to wrap the inner text inside a <span> element when the page is first loaded
// Get all the elements generated by ValidationMessageFor() that have an error
var errors = $('.field-validation-error');
$.each(errors, function (index, item) {
// Wrap the text in a span element
$(this).wrapInner('<span></span>');
})
Note that the jquery.validate plugin also adds an id attribute to the span based on the property name. It does not appear that you need that based on your css, however, if you do want to include that, then you can use
$.each(errors, function (index, item) {
var id = $(this).data('valmsg-for').replace(/[\.\[\]]/g, "_") + '-error';
var span = $('<span></span>').attr('id', id);
$(this).wrapInner(span);
})
Another option would be to wrap each ValidationMessageFor() inside an element, for example
<span class="error">
#Html.ValidationMessageFor(...)
</span>
and modify the css selector
.error > .field-validation-error:before {
font-family: 'icomoon';
....
}

Hide div tag on page load

I have some div's in my project which has some animation on mouse-over done using java-script.
Now my problem is on page load i need to hide all the div's and display only title of the div,and on mouse-over of this title i should be able to make the div visible with all the animation done.
Below is my code:
<div id='Qhse' class="item user">
<h2>qhse</h2>
<div id='qhse' class="qhse" runat="server" >
</div>
</div>
<div id='Policies' class="item home">
<h2>policies</h2>
<div id='policies' class="policies" runat="server" >
</div>
</div>
CSS
#qhse{
padding-top: 0.3em;
padding-bottom:0.3em;
background-color: #2C6D2C;
width: 100%;
height: 100%;
text-align: center;
vertical-align:middle;
}
#policies{
padding-top: 0.3em;
padding-bottom:0.3em;
background-color: #2C6D2C;
width: 100%;
height: 100%;
text-align: center;
vertical-align:middle;
}
JS
$(function () {
$('#nav > div').hover(function () {
visibility: visible;
var field = $('#<%= hdnSelected.ClientID %>');
field.val(this.id);
var $this = $(this);
$this.find('div').stop().animate({
'width': '100%',
'height': '100%',
'top': '-25px',
'left': '-25px',
'opacity': '1.0'
}, 500, 'easeOutBack', function () {
$(this).parent().find('ul').fadeIn(700);
});
$this.find('a:first,h2').addClass('active');
},
function () {
var $this = $(this);
$this.find('ul').fadeOut(500);
$this.find('div').stop().animate({
'width': '52px',
'height': '52px',
'top': '0px',
'left': '0px',
'opacity': '0.1',
'visible': 'false'
}, 5000, 'easeOutBack');
$this.find('a:first,h2').removeClass('active');
});
});
Here is a Working Fiddle.
Added this to Document Ready.
$('#policies,#qhse').hide();
And following minor errors fixed.
visibility: visible;
'visible': 'false'
Still not able to figure out where <ul> tags are. Hide,Hover works fine.
First, a bunch of remarks:
There is no #nav in your HTML.
visibility: visible; inside a function is not a valid JavaScript.
'#<%= hdnSelected.ClientID %>' looks like you're generating your JavaScript using a server-side language. If you do, don't do it. If you don't (i.e. if it's some client-side template engine I've never seen before), make sure this line is doing what you expect it to do.
Make sure $this variable is declared.
What have you tried?
You already have your animation. What you want to do next is to show and hide elements. A simple Google search leads you to the jQuery function show(); similarly, there is a hide() function.
How can you apply those two functions to your actual code?

How to disable the buttons of other URL opening using Iframe?

I m using iframe to open another webservice. there user can view the complete the nav of the targeted link. but i wan't to prevent the user to view the complete nav.
There are five items in the targetd URL like this:
Overview
Call Log
Terrif
Payment
Logout
<iframe id="subframe" frameborder="0" scrolling="no" src="login.aspx" style="float: left;height: 754px; margin-left: 118px; width: 727px;" ></iframe>
Now what i want is that, allow user only to view the Call Log.
How could be this possible to do?
Which steps could be taken to perform these all?
If the service is on your own domain, you can access the frames DOM like so:
var myFrame = frames["myFrame"]
var cssLink = document.createElement("link")
cssLink.href = "iframeStyles.css"; /* change this to the url for a stylesheet targetting the iframe */
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['myFrame'].document.body.appendChild(cssLink);
Also see this question:
How to add CSS class and control elements inside of the Iframe using javaScript.?
If the iframe loads a page from another domain, you may not alter it, because that would be against the same origin policy.
I used this a couple of months before.. Some edits might be required:
<div id="IframeWrapper">
<div id="iframeBlocker">
</div>
<iframe id="mainframe" src="http://www.xyz.com/"></iframe>
</div>
CSS:-
#IframeWrapper
{
position: relative;
}
#iframeBlocker
{
position: absolute;
top: 0;
left: 0;
width: 700px;
height: 450px;
}
#mainframe
{
overflow: hidden;
border-width: 0px;
}
OTHER ALTERNATE AND A BETTER ONE

JQuery BlockUI progress indicator in every Asp.net postback

I would like to implement a jquery blockUI to popup and show a progress indicator (loading circle) during postbacks in Asp.Net. How can I implement this? I am using masterpages so I was wondering if I can implement this code in one place to keep it simple. Is this even possible? Looking forward to hear your thoughts on this.
Thanks in advance.
I was able to develop this. I have included the steps in answers. Let me know if you have questions.
I figured it out myself.
Create a new Asp.net web project.
Include the following in Site.Master markup:
<script type="text/javascript" src="../Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="../Scripts/jquery.blockUI.js"></script>
<script language="javascript" src="../Scripts/General.js" type="text/javascript"></script>
<style>
div.blockOverlay {
background-color: #666;
filter: alpha(opacity=50) !important;
-moz-opacity:.50;
opacity:.50;
z-index: 200000 !important;
}
div.blockPage {
z-index: 200001 !important;
position: fixed;
padding: 10px;
margin: -38px 0 0 -45px;
width: 70px;
height: 56px;
top: 50%;
left: 50%;
text-align: center;
cursor: wait;
background: url(ajax-loader.gif) center 30px no-repeat #fff;
border-radius: 5px;
color: #666;
box-shadow:0 0 25px rgba(0,0,0,.75);
font-weight: bold;
font-size: 15px;
border: 1px solid #ccc;
}
</style>
Add the following markup in default.aspx:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate><asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" /></ContentTemplate>
</asp:UpdatePanel>
Add a progress indicator image (ajax-loader.gif) to project root
Add the following in General.js
// BlockUI setup
$.extend({
// Block ui during ajax post back
initializeUiBlocking: function () {
if (typeof ($.blockUI) != 'undefined') {
$.blockUI.defaults.message = 'LOADING';
$.blockUI.defaults.overlayCSS = {};
$.blockUI.defaults.css = {};
var request = Sys.WebForms.PageRequestManager.getInstance();
request.add_initializeRequest(function (sender, args) {
request.get_isInAsyncPostBack() && args.set_cancel(true);
});
request.add_beginRequest(function () { $.blockUI(); });
request.add_endRequest(function () { $.unblockUI(); });
}
}
});
$(document).ready(function () {
$.initializeUiBlocking();
});
Have a look at this
http://www.malsup.com/jquery/block/#overview
This works for ajax calls.
And you need to place the following line
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
in a place available to all pages.
Introduction:
To Block the Page when Data is Submitting, we have various options, Either we can use Ajax based UpdateProgress or some jQuery Stuff. But sometime Ajax UpdateProgress not very useful because of complexity. So, the better approch appoach is to use jQuery UI Block Plug-In.
Implementation:
Download jQuery UI Block Plugin from : http://www.malsup.com/jquery/block/
<script type="text/javascript" src="js/jquery.1.4.2.js"></script>
<script type="text/javascript" src="js/jquery.blockUI.js"></script>
$("#<%= btnSubmit.ClientID%>").click(function() {
$.blockUI({
message: "<h3>Processing, Please Wait...</h3>" ,
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
} });
});
The above code is simple code without any AJAX or other complex script.
I found this Article on Website and tested, its work fine

Categories