ASP .net MVC form contenteditable null on submit - c#

I have a contenteditable form I'm trying to POST from a form which will be handled by an Action method but I get null for its POST data.
I first define my form:
<form class="composer-form" name="input" action="~/Articles/ResearchArticles/ArticleSubmit" method="post" onsubmit="return SubmitForm()">
#RenderPage("text-editor-partial.cshtml")
<textarea id="hidden_text_area" style="display: none"></textarea>
<div style="padding-left: 2em">
<input class="btn" type="submit" value="Submit" style="width: 200px">
</div>
As the above code shows, the SubmitForm function will handle the copying of the value of the content editable which looks like this:
function SubmitForm() {
var clr = confirm("Are you sure you want to submit the article?");
if (clr == true) {
var hta = document.getElementById("hidden_text_area");
var content_html = document.getElementById("editor").innerHTML;
hta.value = content_html;
return true;
}
else {
return false;
}
}
The code successfully gets the value from the contenteditable div and puts it in the hidden text value field.
So now I have an action that I get from this like:
[HttpPost]
public ActionResult ArticleSubmit(string postData)
{
return new EmptyResult(); //postData is NULL... why?
}
Setting a breakpoint shows postData as null... What is my stupid mistake :) ?
Thanks!

Your textarea needs a name, otherwise the model binder won't fetch its value when you submit your form :
<textarea id="hidden_text_area" style="display: none" name="postData"></textarea>

Possible solution is to use a hidden input instead of textarea, since it does not have a value, actually the contents are stored in a text.
So in HTML:
<input id="hidden_input" style="display: none" name="data" />
And in Controller:
public ActionResult ArticleSubmit(string data)
{
}

Related

How to pass textbox value using #Url.Action in ASP.NET MVC Core 2.2

In my View i have the following code:
<input type="text" id="createdDate" placeholder="dd/mm/yyyy" />
Download
In my Control i have de following code:
[HttpGet]
public async Task<IActionResult> GetRoomAccessHistory(DateTime createdDate)
{
// TO DO
}
In this particular case, i want to pass the createdDate value that is inside the textbox (createdDate) to my Url.Action(...), so it could be passed as a queryString in my URL.
This action is invoked as a GET request, and in GetRoomAccessHistory control method, i should get my createdDate.
Thank you.
PS
I think the solution should be something like this:
<a href="#Url.Action("GetRoomAccessHistory", "Files", new { createdDate = ??? })" >Download</a>
I have got a possible answer:
<form method="post" enctype="multipart/form-data" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
...
<button type="button" id="downloadRoomAccessHistory"</button>
</form>
<script>
var form = document.getElementById("formGetRoomAccessHistory");
document.getElementById("downloadRoomAccessHistory").addEventListener("click", function () {
form.submit();
});
</script>
This does exactly what i want and it works, but i was trying to find a more nice solution because my experience in ASP.NET MVC is low.
You're using the wrong tool for the job.
Since the Url.Action() helper runs on the server-side, it has already executed when the page was first loaded, and generated a fixed URL which is inserted into the page's HTML. It cannot know what the user later enters into the textbox.
If you want to capture data which a user has entered, it makes more sense to use a form. In this case I've used the BeginForm tag helper to generate a suitable HTML <form> tag:
<form asp-action="GetRoomAccessHistory" asp-controller="Files" method="get">
<input type="text" id="createdDate" name="createdDate" placeholder="dd/mm/yyyy" />
<input type="submit" value="Download"/>
</form>
When submitted, this will generate a GET request to the GetRoomAccessHistory action's URL, and append createdDate as a querystring variable, using the value from the textbox.
For Get request,try to use window.location.href.
<input type = "text" id="createdDate" placeholder="dd/mm/yyyy" />
<a onclick = "navigate()" >
< input type="button" value='Download' />
</a>
<script type = 'text/javascript' >
function navigate()
{
var createdDate = document.getElementById('createdDate').value;
var url = "/Files/GetRoomAccessHistory?createdDate=" + createdDate;
window.location.href = url;
}
</script>
And your solution could be simplified to
<form method = "get" asp-controller="Files" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
<input type = "text" name="createdDate" placeholder="dd/mm/yyyy" />
<button type = "button" onclick="myFunction()">Download</button>
</form>
<script>
function myFunction()
{
document.getElementById("formGetRoomAccessHistory").submit();
}
</script>

How to overwrite one model property in ASP.Net core

I have a model with say 10 properties. A, B, C and so on...
Property A is an array.
For each value in array I generate one tag like this:
<div class="col-sm-10 row">
#foreach (var item in Model.A)
{
<div class="col-sm-1 right-buffer">
<i class="" aria-hidden="true">#item.Text</i>
</div>
}
</div>
When user clicks on some link I should redirect it to the same page, but with Some model property changed. For example:
Current url: my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=
with model ?name=Alex&age=20&from=fr&CurrentA=
If user clicks on <a> with text foo it should be redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=foo
then is clicks on <a> with text bar and it should be now redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=bar
So entire query string (except one parameter) should be preserved to send current model state to server while I want to set one value and redirect it to the same page but with new value.
Eventually, it should acts like postback with one extra value setted to model
Is it possible or I should use JS and perform everything myself?
Manually i solved it like this:
First, create hidden fields for every property in model:
<form asp-controller="search" asp-action="index" method="get" role="form" id="searchForm" asp-antiforgery="false">
<input asp-for="SessionId" type="hidden" name="sessionId" value="#Model.SessionId" />
<input asp-for="Quantity" type="hidden" name="quantity" value="#Model.Quantity"/>
<input asp-for="SortField" type="hidden" name="sortField" value="#Model.SortField"/>
<input asp-for="IsAscending" type="hidden" name="IsAscending" value="#Model.IsAscending" />
<input asp-for="Offset" type="hidden" name="offset" value="0" />
...
</form>
Then, use JS to replace value in hidden field and then submit form. Values from inputs will be autimatically converter in query string, so everything works fine:
function sortDocuments(sortField) {
var sField = document.getElementById('SortField');
var isDescending = document.getElementById('IsAscending');
if (sField.value === sortField) {
if (isDescending.value.toUpperCase() === 'FALSE') {
isDescending.value = 'TRUE';
} else {
sField.value = 'rank';
isDescending.value = 'FALSE';
}
} else {
sField.value = sortField;
isDescending.value = 'FALSE';
}
document.getElementById('searchForm').submit();
}
Not very elegant, but it does its job.

Mutiple buttons on MVC form - get item id in the action controller

I have a view with a list of items. Each item have a textbox and a button.
What is the best way to get the item id of the button clicked in the controller action?
I need the value from the associated textbox in the controller action, so I do not think I can use action links.
There are a number of ways to do this. Some use javascript, others don't. I personally prefer to NOT use javascript for basic functionality, unless your design is itself javascript based (such as using ajax)
For instance, you can have each item be wrapped in it's own form, with a different submit value. Just be careful not to nest forms, as that's not valid HTML.
For instance:
#using(Html.BeginForm("MyAction", "MyController", new { id=1 })) {
<input type="submit"/>
#Html.TextBox("TheValue", "One")
}
#using(Html.BeginForm("MyAction", "MyController", new { id=2 })) {
<input type="submit"/>
#Html.TextBox("TheValue", "Two")
}
public ActionResult MyAction(int? id, string TheValue) {
// if they click the first one, id is 1, TheValue = "One"
// if they click the second one, id is 2, TheValue = "Two"
}
this answer is using jquery - If you do not know how to add jQuery to your view or just simply do not want to use it let me know and I can re-work the answer
I would do something like this
<li>
<input type="text" id="1" name="1" class="whatever" />
<input type="button" value="CliCk mE" class="myButton" />
</li>
<li>
<input type="text" id="2" name="2" class="whatever" />
<input type="button" value="CliCk mE" class="myButton" />
</li>
<input type="hidden" id="myHiddenText" name="myHiddenText" />
then add this jQuery:
<script>
$(function(){
$('.myButton').click(function(){
// this is how to get the closest textbox
// you didn't show your html , maybe .prev() or .next()
var textValue = $(this).closest("input[type='text']").val();
// this sets your hidden field with the value from desired textbox
$('#myHiddenText').val(textValue);
});
});
</script>
now when you submit this form to server you can just use myHiddenText on the server
public ActionResult Index(string myHiddenText = "")
{
// hidden fields in the HTML form automatically get passed to server on submit
return View();
}
The best option would be to use jquery but if you only want to use c# I would suggest the following:
I imagine you are using some sort of repeating statement (for or foreach) to generate your textboxes, so what I would do is create a form inside that foreach this new form would contain your textbox, and foreach item you would pass the textbox id to the form submit.
something like this pseudo code:
foreach(item in array){
<form action="address/"#item.Id>
<input type="text" value=""/>
<input type="submit" value="submit textbox"/>
</>
}

calculate button pressed - retrieve rates from database

I need to link to the database (finance rates) when someone enters a number in the text box and clicks calculate that it will pull the rates from the database and display the calculation below in a 'form message'. What should I put in the homecontroller/index to link the code to the database?
Index.aspx:
<td>You wish to convert:
<input type="text" name="amount" size="30" onblur="test_ifinteger(Index.amount,'amounts')"/>
<input type="submit" name="submitter" value="calculate" />
<tr><td colspan="2">That will produce:<%=ViewData["formmessage"] %></td></tr>
Home Controller:
public ActionResult Index()
{
financeInit();
if (Request.Params["submitter"] == "calculate")
calculatepressed();
return View();
public void calculatepressed()
{
.............
}
I would wrap your fields in a form like this:
<form action="Home" method="get">
<div>
You wish to convert:
<input type="text" name="amount" size="30" id="userValue" onblur=""test_ifinteger(Index.amount,'amounts')"/>
<input type="submit" name="userSubmit" />
<br />
That will produce:<%=ViewData["formmessage"] %>
</div>
</form>
Then have your controller something like this:
public ActionResult Index()
{
int value;
if (int.TryParse(Request.Params["amount"], out value))
{
ViewData["formmessage"] = calculatepressed(value);
}
return View();
}
private string calculatepressed(int value)
{
// Do your magic here and return the value you calculate
return value.ToString();
}
If this ever expands from a simple page you might want to consider changing the form action to a post and having two different methods handling the initial view of the home page and the a view for the results of the calculation.

MVC: Retrieving form values after submitting

I have a form on a dialog box like so:
<form action="../ControlerFunction">
<input type=text id="id1"/>
<input type=text id="id2"/>
<button type="submit"> OK </button>
<button type="button" class="close"> Cancel </button>
</form>
When the form is submitted it hits my controller function, but how can I retrieve the values of the two text boxes?
Also when I change the form action to:
<form action="JavaScriptFunction();">
or:
<form action="JavaScriptFunction();return false;">
and I have my JavaScript on the same page as:
function JavaScriptFunction()
{
alert("Hi!");
}
it does not hit the function. Am I missing something?
In your controller add another action method that accepts an HTTP POST and takes in the form collection.
Like:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ControllerFunction(FormCollection collection)
Kindness,
Dan
Correct html form tag syntax:
<form method="post" action="/controller/method/" onsubmit="yourJSFunction();">
...
This suits ALL server-side languages and technologies.
Try considering this first:
FORM Tag needs method(POST or GET);
Your INPUT tags don't have name
attributes which will be used for
accessing the values.
Additional code:
<form name="form1" method="POST" onSubmit="JavaScriptFunction(); return false;">
<input type=text id="id1" name="id1"/>
<input type=text id="id2" name="id2"/>
<button type="submit"> OK </button>
<button type="button" class="close"> Cancel </button>
</form>
javascript:
function JavaScriptFunction()
{
var id1Text = document.form1.elements["id1"].value; //get the value of id1
var id2Text = document.form1.elements["id2"].value; //get the value of id2
//do whatever you want here.
}
Further to #Daniel.
You can either use MyAction[FormCollection collection] and then pull your values from the collection object.
Or, if you have a model that you passed to the view you can use TryUpdateModel() to propergate your model with the values from the form.
If you need more then post a comment and I'll add code.
Going home now so there will be a delay as I fight the traffic. :)
Oh, and welcome to SO.
I want to answer your first question.
how can i retreive the values of the two text boxes?
One answer is given by Daniel Elliot.
After giving you input tags a name attribute with the same value of the id attribut, you can access the values as parameters to your action method.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ControllerFunction(String id1, String id2)
Your second question about java script is answerd by Sergei
<form name="form1" method="POST" onSubmit="JavaScriptFunction(); return false;">
<input type=text id="id1" name="id1"/>
<input type=text id="id2" name="id2"/>
<button type="submit"> OK </button>
<button type="button" class="close"> Cancel </button>
</form>
javascript:
function JavaScriptFunction()
{
var id1Text = document.form1.elements["id1"].value; //get the value of id1
var id2Text = document.form1.elements["id2"].value; //get the value of id2
//do whatever you want here.
}

Categories

Resources