I have an asp.net mvc4 application in which i'd to use the .post ajax's function to post a variable in my view. i had this problem and i posted it here : question, so i'm now trying to solve it by the use of Ajax
View : index.cshtml
<td>
Donner votre avis.
</td>
and
<form method="Post" action="/User/Validate_Expert_Decision" target="_parent">
<span>
<b style="color:red" >
Votre justification *
<b />
<br />
<br />
<textarea rows="10" cols="75" name="justification"></textarea>
</span>
<input type="hidden" name="element" value="#Request.Params["element"]" />
<p>
<input type="submit" name="submit">
<input type="button" name="cancel" value="Annuler" onClick="closebox()">
</p>
</form>
the javascript function
function openbox2(formtitle, fadin) {
var self = $(this);
var arr = self.data('arr');
$.post("/index.cshtml", { element: arr });
var box = document.getElementById('box');
document.getElementById('shadowing').style.display = 'block';
var btitle = document.getElementById('boxtitle');
btitle.innerHTML = formtitle;
if (fadin) {
gradient("box", 0);
fadein("box");
}
else {
box.style.display = 'block';
}
}
controller : Validate_Expert_Decision
public ActionResult Validate_Expert_Decision()
{
string id_element = Request.Params["element"];
return RedirectToAction("Display_Task_List", new { id_project = id_project});
}
the problem is that i always get an empty value of id_element in string id_element = Request.Params["element"];.
What are the reasons of this error? How can i fix it?
If you want to post an ajax request you must use urls in this pattern:
/Area/Controller/Action
in your ajax request you specify your view name, but url for ajax request must be:
$.post("#Url.Action("ActionName, ControllerName, new { Area = "AreaName" }")", { element: arr });
and if you don't have area, just remove last argumant.
Instead of Request.Params["element"] you can easily get your variables by argumant in your action method:
public ActionResult Validate_Expert_Decision(string element)
** If you want to learn ASP.Net MVC i suggest you to read this book:
Pro ASP.Net MVC 4
This is one of best books that i have read until now
Related
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>
Here is my current setup to upload a file to my webapp:
HTML:
<iframe name="myframe" id="frame1" class="hidden"></iframe>
<form target="myframe" method="post" enctype="multipart/form-data" action="/api/User/collection">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
Controller:
// POST api/user/collection
[HttpPost("collection")]
public ActionResult<IResponse> SetCollection(IFormFile file)
{
var collection = fileDeflator.UnzipAndGetCollection(file);
if (collection == null)
return BadRequest(new BaseResponse("The collection file is invalid."));
return base.SetUserCollection(collection);
}
It's working, except that there is no feedback at all for the client.
I would prefer that the JSON returned by the server be caught in a javascript callback on the web page (not the iframe) and be parsed to refresh a section on the page.
Is that possible with the nature of form submit ?
I ended with something working as I wanted with the helpful resources that Amy provided.
Here is the solution:
<form id="formSendCollection">
<input type="file" id="fileCollection" name="fileCollection" />
<span onclick="submitCollection();" class="button is-primary">Submit</span>
</form>
function submitCollection() {
var fdata = new FormData();
var fileCollection = document.getElementById('fileCollection').files[0];
fdata.append("fileCollection", fileCollection);
sendAjax('/api/User/Collection', fdata, function (body) {
vueApp.modelUser.collection = JSON.parse(body);
});
}
function sendAjax(url, body, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('POST', url, true);
xmlhttp.send(body);
}
What I want to do is so simple, I'm still trying to learn ASP.NET with c# and MVC application but I'm just having a lot of difficulty getting a simple example to go through, then I can grow from it, here's how it goes: I have a simple html5 form that's method is GET, the type is text and I basically want to submit a text into my mvc controller, once my controller get's it, I want it to output that string 'worked' through HTML5, how do I do this?
summary: string 'worked' --> html form --> c# controller --> html (view?)
here's what I got for my 'view' (Search.cshtml)
<form action="Home/Search" method="get">
<input type="text" name="q" />
<input type="submit" value="Search" />
ok, so far so good, if I input 'worked' nothing is going to happen unless I add more code, here's c# (HomeController.cs):
public ActionResult Search(string q)
{
return this.View(q?); // so what exactly is View(q)? what is view returning? }
okay so this is where I am confused, does my string go through and become stored in 'q'? and if so, how do I get this thing to use HTML5 to output something like
<p> q </p> <!-- q = 'worked' -->
In your controller, you are calling the View(...) method incorrectly. The View(...) method expects the string parameter you're passing to be the path to the razor view you're trying to render.
A quick and simple way to pass the q variable from your controller to a view to be rendered is using ViewBag.
If you have a razor view named /Views/Search.cshtml you would do:
public class MyController : Controller
{
public ActionResult Search(string q)
{
ViewBag.Query = q;
return View("~/Views/Search.cshtml");
}
}
Then in /Views/Search.cshtml use it like this:
<p>#ViewBag.Query</p>
If you are using asp.net mvc, then please follow mvc pattern like this ..
View
#using (#Html.BeginForm("Search","Home",FormMethod.Post))
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Controller
[HttpPost]
public ActionResult Search(string searchTerm)
{
return View(searchTerm);
}
}
Search.cshtml
<form action="/Home/Search" method="get">
<input type="text" name="q" />
<input type="submit" value="Search" />
</form>
<p class='current-query'>#Model</p>
HomeController.cs
public ActionResult Search(string q)
{
return View((object)q); // return the model to the view (a string)
}
I have a form that you enter data into and it performs a calculation on it and give an answer. what i want to do is for it to keep the data in the form so that you can quickly repost so that you don't have to change all the data. but I cant keep coming up with the error of it not existing, which I suppose is correct until the form has been posted!
#{
var total = 0m;
var totalMessage = "";
if (IsPost)
{
var age = Request["frmage"].AsInt(0);
var weight = Request["frmweight"].AsDecimal();
var SerCre = Request["frmSerCre"].AsDecimal();
var sexfactor = Request["frmGender"]== "M" ? 1.23m : 1.04m;
total =Convert.ToDecimal ((((140 - age)*weight)* sexfactor )/SerCre ) ;
totalMessage = total.ToString("0.00") + "(ml/min) ";
}
}
<div class="memberRegistration">
<form method="post">
<p>
<label class="formLabel">Age:</label> in years
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
</p>
<p>
<label class="formLabel">Weight:</label> in Kg (1st = 6.35kg)
<input class="formTextField" type="text" name="frmWeight" value="#weight"/>
</p>
<p>
<label class="formLabel">Serum Creatinine:</label> in μmol/L
<input class="formTextField" type="text" name="frmSerCre" value="#SerCre"/>
</p>
<p>
<label class="fieldLabel">Gender:</label>
<select name="frmGender" id="select" value="#sexfactor">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</p>
<p><input type="submit" value="Calculate" /></p>
</form>
<p>Calculated creatinine clearance <b>#totalMessage</b></p>
</div>
Try this
var age = 0;
if (IsPost)
{
age = Request["frmage"].AsInt(0);
}
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
But normally it would be better to use a model to hold your values, then in your controller you pass those values back again to your form
Enable the ViewState of the page and controls and also use aspx control, not HTML.
I don't thing that i realy understand the Question because the default thing is that the web page keeps it's view state so the data will still be the same after the post back but here's the solution :
you can simply use ASP Controls because it keep it's view state
or you can give each control of them it's value in the C# , you can assign to each control it's value back
Hope I Helped
Since you are using ASP.NET MVC Razor, what you can do is, do not submit the form using <input type="submit" value="Calculate" /> , instead change it to a simple button like
<input type="button" value="Calculate" onclick="javascript:Submitform();" />
and submit the form using Jquery POST.e.g. like below
function SubmitForm(){
var formData = $("form").serialize() ;
var submitUrl = 'yourURL' ;
$.ajax({
type : 'POST' ,
url : submitUrl ,
data : formData ,
success : function (data ){ alert ("Request successful") ;}
error : function (jqXHR, status , errorthrown) { alert ("error Occured");}
});
}
Still kind of new to MVC, so please bear with me. I'm trying to grab some dynamically generated HTML. In this case, list items in my notifyList. I plan on looping through each one in the controller and adding them as database entries. Any help is appreciated, thanks.
View
#model _BaseViewModel
// The form it's within...
#using (Html.BeginForm("Create", "Leaf", FormMethod.Post, new { id = "createForm" }))
<div class="editor-label bottom-area bottom-header">
Notification List:
</div>
<div class="editor-field bottom-area">
<ul id="notifyList"></ul>
</div>
Controller:
[HttpPost]
public ActionResult Create(_BaseViewModel model)
{
// Some loop here
// get html here
db.UserItems.AddObject(model.user);
db.SaveChanges();
//
return RedirectToAction("Index");
}
As far as I understood, you use jQuery to fetch <li/> elements into notifyList. What you need to do here is to generate a hidden input as well. Sample:
$("#btnAppend").click(function() {
for(var i = 0; i < 4; i++) {
var _val = "Foo " + i;
var $li = $("<li/>").text(_val);
var $hidden = #("<input/>").
attr("type", "hidden")
attr("name", "foo").
val(_val);
$hidden.appendTo($li);
$li.appendTo("#notifyList");
}
});
This code will generate following output inside your DOM:
<ul id="notifyList">
<li>Foo 0<input type="hidden" value="Foo 0" name="foo" /></li>
<li>Foo 1<input type="hidden" value="Foo 1" name="foo" /></li>
<li>Foo 2<input type="hidden" value="Foo 2" name="foo" /></li>
<li>Foo 3<input type="hidden" value="Foo 3" name="foo" /></li>
</ul>
When you make a http form post, you can grab the values by the below controller action implementation:
public ActionResult Index(string[] foo) {
foreach(var item in foo) {
//Work with each individual item
}
//continue your code
}
it doesn't work this way. html only exists in the view. the controller has no concept of html (not should it). data sent to the controller comes in 1 of types (GET, POST). there are others, but these are the main to.
get is typically associated with the querystring www.domain.com/mypage.aspx?key=value
where post is the input values from form
<form action="mypage.aspx" method="post">
<input name="key" value="value"/>
<input type="submit" value="click me"/>
</form>
So adding items to a html list won't provide any meaning to the controller. javascript and ajax provide more options on how the data gets sent to the server, but the data is sent, not the markup. and the data is sent as key value pairs.