I'm doing a project in visual studio mvc4 c# trying to send a string from a JavaScript function in a View to a controller. I tried to use the Session Object like this:
in the View:
Session["matStr"] = matrixString;
in the Controller:
var s = (string)Session["matStr"];
but when I get to the controller the Session returns me null.
so I'll be glad to know the answer how to send a JS' string from view to controller thank in advance..
You can use the following code to call a controller Action
$('#btnSendData').click(function() {
//Send batch to the server
$.ajax({
type: 'POST',
url: '#Url.Action("SessionUpdate")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(sessionvalue),
success: function(result) {
alert(result);
}
});
return false;
});
Here SessionUpdate is a conroller action and you can set the session value as sent in sessionvalue variable and can get the result.
use input hidden field
<input type="hidden" id="hid1" runat="server"/>
$("#hid1").val("the val from client to server");
then get the value in server side.
i hope that thats what you need.(use the string in server side).
you can also just use some span to set the string in controller
You need to include a name for the input. This is what MVC uses to communicate with the View and controller for POSTS.
<input type="hidden" id="hid1" name="hid1"/>
$("#hid1").val("string");
Then on your controller action you use it as a parameter.
public ActionResult Index(string hid1)
{
return View()
}
Related
I have seen lots of questions regarding this issue but none of those resolved my problem.
My problem: my redirect action method hits the method I am redirected to, but the view stays on the same page it never changes to the redirected one.
From my Index.chstml I am creating a partial view.
From that partial view using AJAX I am submitting a request to my controller. AJAX code is below
$.ajax({
method: 'POST',
url: "/Home/SubmitTest",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(arr),
success: function (response) {
}
});
My controller code is here. I am receiving data from AJAX method and performing some jobs. In the end, I am trying to redirect the user to another method.
[HttpPost]
public IActionResult SubmitTest([FromBody] List<TestSubmitViewModel> data)
{
// Rest of the code goes here
return RedirectToAction(nameof(PipelineList));
}
The method I am redirecting to is below. Both methods are in the same controller. After redirection, I am getting hit to this method. But my view still stays in the previous URL which is
https://localhost:44339/Home/Index
but it supposed to redirected to
https://localhost:44339/Home/PipelineList
Code:
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> PipelineList()
{
List<PipelineViewModel> itemList = new List<PipelineViewModel>();
/// my other code goes here
return View(itemList);
}
Note: my PipelineList() works fine when I am coming to this action method directly from UI. What am I doing wrong here and what can I do to redirect to the URL?
I am using .NET Core 5.
Here is my routing information from StartUp.cs:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action="SignIn"});
});
UPDATE
Thank you guys for pointing out the problem I was having.
Using AJAX was necessary for me to pass the selected values (which were from a table created by JS) from UI.
Finally, I made it work by changing my Controller and AJAX code.
Updated Controller:
[HttpPost]
public async Task<JsonResult> SubmitTest([FromBody]
List<TestSubmitViewModel> data)
{
try
{
// my codes goes here
return Json(new {StatusCode = statusCode });
}
catch (Exception)
{
return Json(new {StatusCode = 500 });
}
}
Updated AJAX:
$.ajax({
method: 'POST',
url: "/Home/SubmitTest",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(arr),
success: function (response) {
if (response.statusCode == 200) {
var url = "/GitLab/PipelineList";
window.location.href = url;
} else {
alert("error");
}
}
});
I know this might not be the best solution but for now, it did work. Thanks a lot to #Sergey and #Filipe
As #Sergey says, you used the wrong senior for ajax. Ajax is normally used when you want to update part of the page instead of refreshing the whole page to increase the customer experience and page load speed. If you want to redirect to another page and there is no other specific reason, there is no need to use ajax.
You could find the ajax server has returned the right 302 redirect to the client side and it redirect to the new page:
The right way is directly redirect to the new page like this:
<form asp-action="SubmitTest" asp-controller="Home" method="post">
#*Other input value you want to submit*#
<input type="submit" value="Click"/>
</form>
Result:
I'm sending some json data with ajax by post
function SendF() {
$.ajax({
url: '#Url.Action("Summary")',
type: 'POST',
data: JSON.stringify(flags),
contentType: "application/json;charset=utf-8",
success: function() {
},
error: function() {
alert("Oops! We've experienced a connection problem!");
}
});
}
to my controller
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
[...]
return View(flags);
}
and tried returning a view with data I've processed, but I guess it's not gonna happen since ajax is all about asynchronous http requests. How do I change my code to be synchronous?
The whole idea behind using ajax is to give the user the partial page update experience. If you are making an ajax call and once that is done and you are doing a redirect to another page, it does not give the partial page update experience to user. It looks very similar to the normal form submit(full page submit).
If you absolutely have to send the data to server via ajax , but want to do the redirect after the ajax call is successfully finished, you can do that using javascript in the success or done callback event on the $.ajax method.
All you have to do is, set the location.href property to the new url.
var flags = ["aa", "bb", "cc"];
$.ajax({
url: '#Url.Action("Summary")',
type: 'POST',
data: JSON.stringify(flags),
contentType: "application/json;charset=utf-8"
}).done(function(res) {
window.location.href = res.newUrl;
}).fail(function(xhr, a, error) {
console.log(error);
});
This assumes that your server action method returns a JSON response with the newUrl property which contains the url you want to redirect to .
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
return Json(new { newUrl = Url.Action("Index","Home") });
}
One way to do this would be to send the request to the controller via ajax and then render a partial view on your page. The easiest way would be to use the built in ajax helpers in ASP MVC. Here is a link to another post that gives a pretty good overview:
How to render partial view in MVC5 via ajax call to a controller and return HTML
I need to pass data from View to Controller(From TestView1 to TestController2)
#Html.ActionLink("Text", "Index", "Sample", new { testId = test }, null)
Currently this is sending Data in QueryString. But i need to avoid this and pass data to Controller without Query string ?
How do i achieve without Querystring ?
I searched and most of them were by using Query string. If i missed out on solutions please redirect to correct path.
Thanks
Have you tried to post your data to the controller, if possible? Keeping a form and hidden fields..
e.g http://www.asp.net/ajaxlibrary/jquery_posting_to.ashx
You can send data using Ajax call back. try this method on your link/button
#* Your button/link *#
<input type="button" onclick='Link1()'" value="Submit" />
<script type="text/javascript">
function Link1() {
var Id = $("#txt").val();
$.ajax({
url: '#Url.Content("~/Test2/Actionname")',
type: 'post',
async: true,
data: { text: Id },
success: function (data) {
alert("Success");//Ajax request success
alert(data);//data from Test/yourAction
},
error: function (err) {
alert("fail");//Ajax request fail
alert(err.responseText);//error will displayed here
}
});
}
</script>
I'm using Html.Beginform in view page and get the parameters using FormCollection to the controller i want to return the Success message on the same ViewPage as a result.i'm using following code,
public string InsertDetails(FormCollection collection)
{
string result = "Record Inserted Successfully!";
return result;
}
It shows the success message on the new page.How can i resolve this? what i have to return to get the Success message on the same page?
Personally, I'd pop the result string into the ViewBag.
public ActionResult InsertDetails(FormCollection collection)
{
//DO LOGIC TO INSERT DETAILS
ViewBag.result = "Record Inserted Successfully!";
return View();
}
Then on the web page:
<p>#ViewBag.result</p>
I have following Options.
1. Use Ajax Begin Form with AjaxOptions like below
#using (Ajax.BeginForm("ActionName", "ControllerName", new { area = "AreaName" }, new
AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "alert('Success');" //This will execute once the Ajax call is finished.
}, null))
{
<input type="submit" name="nameSubmit" value="Submit" />
}
2. Use JQuery to Manually Setup the XHR Request
$.ajax({
url: "#Url.Action("ActionName", "ControllerName", new { area = "AreaName" });",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({param : Value})
})
.done(function () { alert('Success');}) //This will execute when you request is completed.
.fail(function () { })
My Suggestions
There are following disadvantages while using the FormCollection
Point - 1
In case FormCollection is being used...It will be mandatory to Type Cast the Primitive Type Values un-necessarily because while getting the entry of specific Index of the System.Collections.Specialized.NameValueCollection, value being returned is of type String. This situation will not come in case of Strongly Typed View-Models.
Issue - 2
When you submit the form and goes to Post Action Method, and View-Model as Parameter exists in the Action method, you have the provision to send back the Posted Values to you View. Otherwise, write the code again to send back via TempData/ViewData/ViewBag
Point - 3
We have Data Annotations that can be implemented in View Model or Custom Validations.
ASP.Net MVC simplifies model validatons using Data Annotation. Data Annotations are attributes thyat are applied over properties. We can create custom validation Attribute by inheriting the built-in Validation Attribute class.
Point - 4
Example you have the following HTML
<input type="text" name="textBox1" value="harsha" customAttr1 = "MyValue" />
Question : How can we access the value of customAttr1 from the above eg from inside the controller
Answer : When a form get posted only the name and value of elements are posted back to the server. You can also use Hidden Fields to post the Attributes to Post Action method.
Alternatives : Use a bit of jQuery to get the custom attribute values, and post that along with the form values to action method
Another option is to rather put what you got in your custom attributes in hidden controls
That's the reason, I would always prefer to use View-Models
we can do it on Form inside view
#using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { HttpMethod = "POST", OnSuccess = "Showmessage" }))
[HttpPost]
public ActionResult Test(TestViewModel model)
{
return Json(new {isok=true, message="Your Message" });
}
function Showmessage(data)
{
$('#Element').html('Successfully Submitted');
}
I reallly have a simple set of code to bring back a set of data that is triggered off a drop down.
this is the script:
function () {
$('#ProviderID').change(function () {
$.ajax({
url: '/servicesDisplay/Index',
type: 'Get',
data: { id: $(this).attr('value') },
success: function (result) {
// The AJAX request succeeded and the result variable
// will contain the partial HTML returned by the action
// we inject it into the div:
$('#serLocations').html(result);
}
});
});
This is the controller:
public ActionResult Index(string id)
{
int prid = Int32.Parse(id.Substring(0, (id.Length-1)));
string mulitval = id.Substring((id.Length-1), 1).ToString();
System.Data.Objects.ObjectResult<getProviderServiceAddress_Result> proList = theEntities.getProviderServiceAddress(prid);
List<getProviderServiceAddress_Result> objList = proList.ToList();
SelectList providerList = new SelectList(objList, "AddressID","Address1");
//ViewBag.providerList = providerList;
return PartialView("servicesDisplay/Index", providerList);
}
This is the view:
#model OCS_CS.Models.servicesDisplay
<div>
#Html.DropDownList(model => model.ServiceAdderssID, (IEnumerable<SelectListItem>)model)
</div>
When the drop down passes the in the value. The apps does hit the controller. But it highlightes the drop down in a light red and the view never displays.
Try this short version which uses the jquery load method.
$(function(){
$('#ProviderID').change(function () {
$('#serLocations').load("#Url.Action("Index","ServicesDisplay")?id="
+$(this).val());
});
});
If you want to avoid caching of result, you may send a unique timestamp along with the querystring to avoid caching.
$('#serLocations').load("#Url.Action("Index","ServicesDisplay")?id="
+$(this).val()+"&t="+$.now());
You are doing a GET, thats no meaning to pass data to ajax, you may pass data for POST:
First, put the value at the URL:
function () {
$('#ProviderID').change(function () {
$.ajax({
url: '/servicesDisplay/Index/' + $(this).attr('value'),
type: 'Get',
success: function (result) {
// The AJAX request succeeded and the result variable
// will contain the partial HTML returned by the action
// we inject it into the div:
$('#serLocations').html(result);
}
});
});
Second, mark the method as GET
[HttpGet]
public ActionResult Index(string id)
Hopes this help you!
You have quite a few problems with your code. First the model defined for your view is:
#model OCS_CS.Models.servicesDisplay
but in your action your're invoking the call to this view by passing in a SelectList:
SelectList providerList = new SelectList(objList, "AddressID","Address1");
return PartialView("servicesDisplay/Index", providerList);
this is not going to fly because the models do not match by type. Seconds problem is you are casting this SelectList into an IEnumerable. This is also not going to work. You need to cast to SelectList:
#Html.DropDownList(model => model.ServiceAdderssID, (SelectList)model)
but again until you match the type of your model in your action with the model on your view none of this will work. I suggest you install Fiddler to help you determine what sort of error are you getting.