Calling a JavaScript function from a URL action - c#

I need to get the value of an input and pass that to a select2 to get suggestions. How can I call a JavaScript function from a URL action
#* Name *#
<input id="Name" name="AccountName" type="text" value="" autocomplete="off" data-url="#Url.Action("*********", "******")" data-urlonselect="#Url.Action("*****", "*******")">
#* Group / HQ *#
#Html.Select2Ajax("newGroup", Url.Action("******", "****", new { valuefromInput = MyFunction(); }))

I have never used Select2, so there may be some functionality in there that I am unaware of. With that said, the Url.Action() is question is a standard part of the ASP.NET MC framework and I feel relatively comfortable with answering based on that.
Url.Action is a sever side razor directive. That means that all the processing happens on the webserver at the time of the request. It is not, nor can it be, aware of the JavaScript that may execute in the future.
My recommendation would be to create a hidden input, or a non-visible div, and store the output of Url.Action in that container, using a recognizable placeholder for your input value, say "-12." Then, in your javascript that is responding to the changes to the input, you can dynamically replace the place holder with its actual value and set that property accordingly on the select box. You may or may not need to re-initialize your Select2 drop down in with each call.
At least, that is why I would try. Hope this helps! =)

Related

How to locate the input box using C# Selenium

I need to find the input box in this HTML:
<div id="employeesDataTable_filter" class="dataTables_filter">
<label>
<input type="search" class="form-control input-sm"
placeholder="Filter..." aria-controls="employeesDataTable">
</label>
</div>
But for the life of me cannot - please help,
I have successfully written bags of tests and found many page element of different types but this one has stumped me.
I am very new to this and have tried
By ExecutiveSearchBox = By.XPath("//input[#type='search' and
class='dataTables_filter']");
You have encountered problems because you are selecting class attribute on input node instead on div. Try following selector:
//div[#class='dataTables_filter']//input[#type='search']
Also as #Marco Forberg mention it is good to use contain() XPath function in case if there are multiple classes provided for element:
//div[contains(#class, 'dataTables_filter')]//input[#type='search']
I hope it'll help to resolve your issue :)
To find the input element in your html snippet, you simply use
FindElement( By.CssSelector( "input" ) )
But note:
not always is the input box editable after page load is completed, it may take some time. It might be wise to wait until the box becomes editable if you want to send data to it.
not always does the input box appear immediately in the DOM. With modern UI like Angular, it might be not there immediately, might be something else for a while and only later become an input field and the like. Also here, making use of Seleniums wait functionality sure is a good idea.
I ALWAYS wait for the DOM state I expect and only after some time when the state is not achieved I throw.

textarea asp-for doesn't display property

I've been working on a small school project and decided to use .net core (MVC) for the first time. I have a small button I can click which executes the "ipconfig" command in the background and displays the output in a text area. At first my team partner used only a
public string Result;
in ViewModel for the view. In the view it's displayed via
<textarea asp-for="Result"></textarea>
So I decided to make it into a property with default get and set:
public string Result { get; set; }
But when I do that, the output doesn't show up in the textarea if I keep the same approach in the view as my team member did when he used a field instead of a property. Instead I have to do it like this to get it to show up in the textarea:
<textarea>#Model.Result</textarea>
Now I'm asking myself why this happens. Can't I display Properties with asp-for? And what would be better to use, a field or a property as Result?
Many thanks in advance!
In my case this behavior was happening because I did not have a separate closing tag on my textarea. I know your example above has it when using the asp-for method, but in case that was a copy/paste error, you may want to look at that again.
<textarea asp-for="Message" type="text" class="form-control" rows="5" id="MessageInputField" autofocus></textarea>
As opposed to:
<textarea asp-for="Message" type="text" class="form-control" rows="5" id="MessageInputField" autofocus />
This is incredibly annoying 'gotcha' like behavior in my opinion. And maybe if someone wants to tell me why it isn't, then please enlighten me, I'm always willing to learn.
You should actually be using properties, and if <textarea>#Model.Result</textarea> works, <textarea asp-for="Result"></textarea> should as well. The only reason it wouldn't is if the ModelState has a different value for Result (as the latter form actually uses ModelState, whereas the former is obviously using Model directly).
ModelState is composed of values from Request, ViewData/ViewBag, and finally Model, so for example, if you were to do something like ViewBag.Result = String.Empty, that would actually override the value from Model in ModelState.
There's no enough code here to truly diagnose the exact issue, but I would look for other places you might be using "result" (case-insensitive). If you're accepting that as a request param or setting a ViewBag member, etc. that's your problem.
I find this is a bit weird in .Net Core 6, when I want two-way binding - ie displaying the result
With asp-for I have to self close the tag AND add the additional textarea close tag to get the result displayed.
<textarea asp-for="Result" />#Model.Result</textarea>
This works but is not syntactically correct.
Without the self-close tag, the result was not being display
<textarea asp-for="Result">#Model.Result</textarea> #*Does not display the value*#
For display only, this is more correct
<textarea>#Model.Result</textarea>

ASP.Net MVC 5: Html.RenderAction("...") at runtime

I want to add a PartialView multiple times by pressing a button.
<div id="FilterRows">
#{Html.RenderAction("_FilterRow");}
</div>
<button id="newRow" type="button"
class="btn btn-sm btn-default"
style="width: 50px">+</button>
This piece of code works properly. But now i want to append the div FilterRows with another PartialView of _FilterRow at clicking on the button.
This is how it looks today:
Something like:
$(document).ready(function() {
$("#newRow").click(function() {
$("#Exec").append("<br>", #{Html.RenderAction("_FilterRow");} {
});
});
});
Is unfortunately not working. Any Ideas?
If you add an action which returns the partial rendered as a partial (ie. return PartialView("myView", model); then you can load using jQuery:
# Create a new element to contain...
var el = $('<div></div>');
$('#parent').append(el);
# ...the new content
el.load('#Url.Action("action", "controller"');
(This means running the JS in the razor view to get the correct URL generation. If most of the JS is in its own file, pass the URL from a little JS in the Razor file just for things like URLs.)
As long as your script is in the page (and not in an external .js file) you can use Razor inside js (although feedback directly from MicroSoft indicates that this is "unexpected", it works fine).
Have a look at the rendered html to see what's wrong.
In this case you need quotes (") around the render action:
$("#FilterRows").append("#{Html.RenderAction("_FilterRow");}");
This assumes a number of potential issues:
the 'RenderAction' can't have any newlines in the output
the 'RenderAction' can't have any quotes in the output (either use ' on the append and " inside the render or the other-way-around)
the action to be rendered cannot have any row-specific parameters (which appears to be ok in this case to add a new blank row)
the script must be in a .cshtml file (though you can get around this by setting a global/namespace'd variable in the .cshtml and have the actual code in a .js file)
you need to use the correct combination of #{}/#() and render/tostring
You might be better off with #Html.RenderPartial if you just want to render some html and don't need an action.
An alternative, perhaps more friendly, mechanism would be to have the blank-row already on the page (perhaps hidden) and use .clone().

Moving text in .Net without refreshing page

I am still new to the coding field and am having a bit of trouble with a part, hoping someone can help me. I am working on a MVC page where i am trying to move text, the user inputs, around the page to a few pre-set spots and without having to refresh the page. Do i need a type of script for this? And if i do what would be best? Thanks for the help.
You can do it this way.
Enter Text here... <input id="testText" type="text" onKeyUp="javascript:showText($(this), event);"/>
<br/>
<br/>
<br/>
See it here... <span id="testTextSpan"></span>
Then, add this script...
<script type="text/javascript">
var showText = function (el, e) {
$('#testTextSpan').html(el.val());
};
<script>
See it here in this JSFiddle...
http://jsfiddle.net/ZEcNp/
Be sure to include JQuery libraries in your project, or reference the CDN.
If you'd like me to include an example with raw javascript, with no JQuery, I can also provide that for you.
I would recommend jQuery to do all that client-side.
You would just need an ID for each element you would use as the predefined spots, using either .appendTo, .insertAfter, .html, or something else depending on your exact needs.

Can't get text from CKEditor MVC3

Im new at Asp.Net MVC3, and i was trying to use CKEditor. But can't get my typed text then i push submit.
My View:
<form method=post action="#Url.Action("Description")">
<textarea class="ckeditor" id="editor1" rows="10" name="Details">#Resources.Resources.DescriptionSampleText</textarea>
<input type="submit" />
</form>
And the controller there i need the text:
[HttpPost]
public ActionResult Description(string textdetails)
{
//Doing something with the text
return RedirectToAction("Create", "Project", new { text = textdetails});
}
What am I doing wrong?
There are three solutions to your problem. I will start of with solving it directly (two ways), however, in my opinion it is not the best way. Anyway, more about that later.
ASP.NET MVC (3) works a lot convention-based. It will magically assign values etc. from requests to parameters and other. Of course, these conventions are obviously based upon the names of your parameters. You'll have to make sure that your names match (as you might figure out right now, this will be a pain-in-the-a to maintain).
The quick solution is to name your textarea in your view the same as your parameter of your HttpPost action. Your view code would look like this:
<form method=post action="#Url.Action("Description")">
<textarea class="ckeditor" id="editor1" rows="10" name="Textdetails">#Resources.Resources.DescriptionSampleText</textarea>
<input type="submit" />
</form>
This should work. Note: I didn't test this myself right now, however many beginners guides do this as well, so I figure that will work. Anyway, I really don't like this solution, because it is really a hell to maintain (refactoring etc won't be very easy).
A second solution is to use a FormCollection. You give this as a parameter of your HttpPost action and you can access then your value through an index. For an example and more information, you can look at this SO post: https://stackoverflow.com/a/5088493/578843 .
The last solution (which I prefer) is creating a ViewModel. I suggest you read this guide ( http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/examining-the-edit-methods-and-edit-view ) on how to do edit pages etc properly.
And one last thing, if you want to submit HTML as content, you will have to either disable the save guarding of ASP.NET or add a Annotation to your method (or class). Please do not generally disable save guards (it will check input for html etc), only disable it with annotations when needed. You can set the ValidateInput attribute (MSDN link) to false on your action. Example:
[HttpPost]
[ValidateInput(false)]
public ActionResult Description(string textdetails)
{
//Doing something with the text
return RedirectToAction("Create", "Project", new { text = textdetails});
}

Categories