Pass Data from View to Controller - with model - c#

I need to pass some information from the View to the Controller.
Currently, I am doing something like the following:
var url = '#Url.Action((object)#ViewBag.CompID, "Print", "DataRecords")' + '?location=' + model.Location + '&startDate=' + model.StartDateTime + '&endDate=' + model.EndDateTime;
window.location.href = url;
I wanted to hide the location, startdate and end date from showing up in the browser url.
I was thinking about creating a model as shown below and sending the model to the Controller but not sure how to.
var model = {
Location: $('#Location :selected').val(),
StartDateTime: $("#StartDate").val(),
EndDateTime: $("#EndDate").val()
};
Note that in my case, I do not need to retrieve any data back as the Print method will do the printing.
I am open to accomplishing this besides using
window.location.href
How can this be done using AJAX as I do not need to return back to the view with any data as the Print method action will print the the appropriate view.

If you want to pass data from the front end to the back-end controller, you have two ways:
through a GET(passing parameters on the URL)
with a POST that you can do it via AJAX or simply putting your information inside a form with POST action to the method you want to hit in the controller
MVC will do the binding for you, all the information using the POST, for example, should be inside the form, then on the controller, you can create your model as the input and use the default MVC bindings.
My suggestion if you want to hide that information from the url is to do it via a post(inside a form with a submit), but anyways if you click on the Network tab of the browser in both cases you should see the parameters you are passing to your controller.
There are other ways to achieve the same thing as the use of the TempData dictionary, which keeps information for a roundtrip operation between the controller and the view, but I don't recommend to proceed this way, every time I use that as a backdoor to patch my problems I feel guilty

You can do this.
Controller
public class HomeController : Controller
{
public ActionResult HideQueryString()
{
return View("Tut143");
}
public ActionResult Print(string location, string startDate, string endDate)
{
//print here
return RedirectToAction("HideQueryString");
}
public ActionResult Tut143()
{
return View();
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut143</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
var model = {
Location: $('#Location :selected').val(),
StartDateTime: $("#StartDate").val(),
EndDateTime: $("#EndDate").val()
};
var url = '#Url.Action("Print", "Home")' + '?location=' + model.Location + '&startDate=' + model.StartDateTime + '&endDate=' + model.EndDateTime;
window.location.href = url;
})
})
</script>
</head>
<body>
<div>
<select id="Location">
<option value="Arizona">Arizona</option>
<option value="California">California</option>
<option value="Wyoming">Wyoming</option>
<option value="Delaware">Delaware</option>
</select>
<input id="StartDate" type="text" value="default startdate value" />
<input id="EndDate" type="text" value="default enddate value" />
<input id="theButton" type="button" value="Go" />
</div>
</body>
</html>

Related

Error getting shortened URL using tinyurl API

I am trying to make a URL shortener using TinyUrl. The problem is that I get the following error:
System.Net.WebException: 'Error on the remote server: (400) Incorrect request.
I have already tried reading in almost the entire site but I have not found the solution.
The controller code is:
namespace Prueba.Controllers
{
[HandleError]
public class TinyURLAPIController : Controller
{
// GET: TinyURLAPI
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View("Index");
}
[HttpPost]
public ActionResult MakeTinyUrl(string strURL)
{
var tinyUrl = WebRequest.Create("http: / tinyurl . com/api-create.php?url=" + strURL);
var shortUrl = tinyUrl.GetResponse();
using (var reader = new StreamReader(shortUrl.GetResponseStream())){
ViewData["tinyUrl"] = reader.ReadToEnd();
}
return PartialView("Index");
}
}
}
And this is the index code:
<Html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<#Ajax.BeginForm("MakeTinyUrl", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "tinyUrl" }))>
#Html.TextBox("url")
<input id="btnMakeUrl" type="submit" value="Make tinyUrl" onclick="Index" />
</body>
</Html>
I need to enter the long URL in a textbox and pressing the button shows the short URL in a label
Can't comment so i'll just write it as an answer!
Your problem isn't the api request.
Your strURL is probably null as it was for me with your code.
Try making the following change in your view:
from
#Html.TextBox("url")
to
#Html.TextBox("strURL")
and also your html isn't quite valid where you defined the form.
try:
#using (Ajax.BeginForm("MakeTinyUrl", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "tinyUrl" }))
{
#Html.TextBox("strURL")
<input id="btnMakeUrl" type="submit" value="Make tinyUrl" onclick="Index" />
}
It' possible you may have to UrlEncode the value before passing it to the view:
https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=netframework-4.8
I understand you've altered the api link in your post due to restrictions.
firstly i'd manually call the api in your preferred browser using the URL you're trying to shorten...make sure that is ok.
e.g. [redacted]tinyurl.com/api-create.php?url=http://www.yoururltest.com
Next, run a test with a breakpoint, stepping through your code to see exactly where the error happens and view the data your controller receives and uses in the request.
I bet you'll find an issue with that somewhere along the way

MVC, how to post data to controller and redirect to aspx page

I have an MVC view where user can set a flag and post data to controller (post because I want to hidden query string)
After the controller have done his job I want to redirect to website home page that is an aspx page (my site is mixed aspx and MVC)
Is there a way to do that?
This is my view
#model MessaggiVM
<form role="form" class="form-inline" method="post" action="Messaggi/VaiAllaHome">
<button id="btnHome">Vai alla pagina iniziale</button>
<div class="form-group">
<label for="nascondi">hiding</label>
<input id="nascondi" type="checkbox" name="nascondi" value="true" />
</div>
<input type="hidden" name="elencoPost" value="#Model.Posts" />
#*#Html.ActionLink("Messaggi", "VaiAllaHome", new { posts = Model.Posts} )*#
</form>
And this the controller
[HttpPost]
public RedirectResult VaiAllaHome(bool? nascondi = false, IEnumerable<Messaggio> elencoPost = null)
{
// do something
return Redirect(Url.Content("~/"));
}
When I run this code controller action is executed without error but redirect is not done and browser remain on the view
Other problem is that elencoPost parameter is empty in the action but I'm investigating it
EDIT
Honestly I'm thinking to post data on input change and switch button for a simply link
EDIT 2:
found the reason: in default.aspx i have a auto-redirect to Message page :(
Try
return Redirect("~/home.aspx");
or
return Redirect(Url.Content("~/home.aspx")
You should be able to use Redirect with a relative url:
[HttpPost]
public RedirectResult VaiAllaHome(bool? nascondi = false, IEnumerable<Messaggio> elencoPost = null)
{
// do something
return Redirect("/home.aspx");
}
Try using a #Url.Content on your form tag
<form action="#Url.Content("~/Messaggi/VaiAllaHome/")">
Then in your Controller
[HttpPost]
public RedirectResult VaiAllaHome(bool? nascondi = false, IEnumerable<Messaggio> elencoPost = null)
{
// do something
return View(Url.Content("~/"));
//return RedirectToAction("Action", "Controller", new { routeParameter = value } /*e.g. "id = 1"*/);
}

Controller methods when submitting an AJAX request

I have an MVC project that has a page with several forms on it. Most of the content on the page is rendered based on an initial form that a user submits. When a user updates information on that page I don't want the entire page to refresh I just need it to submit the form and stay on the page. I've tried to setup the form to submit with AJAX, but I don't know what to make the controller method return to accomplish this.
Form:
<div id="HeatNameDiv" title="Change Heat Name">
#using (Ajax.BeginForm("ChangeHeatName", "Home", new AjaxOptions(){UpdateTargetId = "HeatNameDiv"}))
{
<section>
Heat Name:<input type="text" name="heatName" value="#Html.ValueFor(x => x.heatname)" style ="width:100px"/>
Change to:<input type="text" name="updatedHeat" value="" style="width: 100px" />
<input type="submit" name="ChangeHeatName" value="Change" />
</section>
}
Current Controller:
public ActionResult ChangeHeatName(string heatName, string updatedHeat)
{
string user = User.Identity.Name;
HomeModel H = new HomeModel();
H.ChangeHeatName(heatName, updatedHeat, user);
return Content("Index");
}
It depends on what you want refreshed. Ajax.BeginForm expects an HTML fragment. So you need a partial that represents the heatNameDiv that you want to replace after submit:
public ActionResult ChangeHeatName(string heatName, string updatedHeat)
{
string user = User.Identity.Name;
HomeModel H = new HomeModel();
H.ChangeHeatName(heatName, updatedHeat, user);
return PartialView("NameOfPartialView", H);
}
I agree with Jeremy because Ajax.BeginForm is less flexible. I have tried hard to use it in the past, but the fact that it replaces the target element, instead of the innerHtml of the target, makes it difficult for many scenarios.
With $.ajax you can set url: '#(Url.Action("MyActionReturningAPartialView"))' and in the .success callback function(response) { $('#heatNameDiv').innerHtml(response); }
The action you call still returns a PartialView.

CKEditor html content lifecycle: asp net mvc case

My content will be edited number of times.So i need to store result html to database and load it again when it is neccessary.Here is my current start implementation:
#using (#Html.BeginForm("EditArticle", "Admin", new { id = ViewData["id"] }))
{
<div id="editor"> </div>
<input type="submit" value="save changes" onclick = "setValue()" />
<input type ="hidden" id="value" name="html" />
}
<script>
var editor, html = 'Model.Text';
function createEditor() {
if (editor)
return;
var config = { width:"900px"};
editor = CKEDITOR.appendTo('editor', config,html);
}
function setValue() {
$("#value").val(editor.getData());
}
createEditor();
</script>
But I get eror with initialization html variable.So, could anyone show how correct encode / decode html?
EDIT
Here is data controller receives:
html = <p>ARTICLE 3</p>\r\n
Values like this I store in database and try insert again.
First things first, to fix your code syntactically, it should probably read something like:
var editor, html = '#Html.Raw(Model.Text)';
However, why not instead of dealing with the markup in JavaScript and having to escape and unescape it, dump it directly where it should go i.e.
<textarea name="editor1">#Html.Raw(Model.Text)</textarea>
<script>
CKEDITOR.replace( 'editor1' );
</script>
And then transform that textarea into your ckEditor? As per their basic example here: http://docs.ckeditor.com/#!/guide/dev_framed
Secondly, aside from that I am not sure what errors you are receiving with your controller, so you will have to post further details for me to help you beyond the above.
I hope this helps.

ASP.NET MVC & JQuery Dynamic Form Content

I would like to dynamically add fields to an ASP.NET MVC form with JQuery.
Example:
<script language="javascript" type="text/javascript">
var widgets;
$(document).ready(function() {
widgets = 0;
AddWidget();
});
function AddWidget() {
$('#widgets').append("<li><input type='text' name='widget" + widgets + "'/></li>");
widgets++;
}
</script>
<ul id="widgets">
</ul>
This works, but I was going to manually iterate the form values in the controller:
[AcceptVerbs("Post")]
public ActionResult AddWidget(FormCollection form)
{
foreach (string s in form)
{
string t = form[s];
}
return RedirectToAction("ActionName");
}
But it occurred to me when I send the user back to the Get Action in the Controller I will have to set the FormData with the values entered and then iteratively add the widgets with <% scripting.
What is the est way to do this in the current release (5 I believe)?
My solution could be something like this (pseudo-code):
<script language="javascript" type="text/javascript">
var widgets;
$(document).ready(function() {
widgets = 0;
<% for each value in ViewData("WidgetValues") %>
AddWidget(<%= value %>);
<% next %>
});
function AddWidget( value ) {
$('#widgets').append("<li><input type='text' name='widget" + widgets +
"'>" + value + "</input></li>");
widgets++;
}
</script>
<ul id="widgets">
</ul>
And in the controller:
[AcceptVerbs("Post")]
public ActionResult AddWidget(FormCollection form)
{
dim collValues as new Collection;
foreach (string s in form)
{
string t = form[s];
collValues.add( t )
}
ViewData("WidgetValues") = collValues;
return RedirectToAction("ActionName");
}
You can work out the details later
(sorry for mixing VB with C#, I'm a VB guy)
i might be missing the point here, but, do you need to actually post the data back to the controller via a form action? why not make an ajax call using jquery to post the data to the controller...or better yet a web service? send the data async and no need to rebuild the view with the data values sent in.
This works fine if the values are being consumed and never used again, however, if you plan on persisting the data and surfacing it through a the view, your model should really support the data structure. maybe a Dictionary<string, string> on the model.
I'm not a ASP.net developer but I know from PHP that you can use arrays as names for input fields
Ex:
<input type="text" name="widgets[]" />
<input type="text" name="widgets[]" />
You can then iterate through the post variable widgets as if it was an array of values.
No messing around with dynamicaly named variables etc.
As far as I understand the problem is to preserve the posted values in widgets.
I thik you can just render those widgest you wont to populate on the server during the View rendering.

Categories