ASP.NET MVC 4 AJAX.BeginForm and PartialViews - javascript

I am considering building a SPA using AJAX.BeginForm, however I am facing an issue when a user has JavaScript disabled, instead of redirecting him to _Layout.cshtml + PartialView.cshtml, it redirects him to just the PartialView.cshtml..
Is there a way to include the Layout and the PartialView in it (where it would be if JavaScript was enabled)?
Thanks
Edit:
Awesome.. Thanks.. I managed to get it working but I am not sure it's the best implementation..
[HttpPost]
public ActionResult Index(Newsletter newsletter)
{
if (ModelState.IsValid)
{
db.Newsletters.Add(newsletter);
db.SaveChanges();
ViewData["message"] = "thanks for signing up to our newsletter!";
if (Request.IsAjaxRequest())
{
return PartialView( "SimpleMessage" );
}
}
return View();
}
And SimpleMessage.phtml is simply just #ViewData["message"];
whereas my View.phtml I have got a condition and checks whether ViewBag["message"] is set or not. If it's set, then it means it's a postback and doesn't show the form and shows the message instead, or else it shows the form:

You can check if Action was called via Ajax, or not, and return different type of result
public ActionResult MyAction()
{
if(Request.IsAjaxRequest()) {
// Html fragment
return PartialView();
}
else {
// Complete HTML page
return View();
}
}
If it's postback, you can pass your model, or simple types (int, string) around as well:
[HttpPost]
public ActionResult MyAction(Model model)
{
if(Request.IsAjaxRequest()) {
// Html fragment
return PartialView(model);
}
else {
// Complete HTML page
return View(model);
}
}
Edit: In your specific case I would do like this, but it's only my preference.
[HttpPost]
public ActionResult Index(Newsletter newsletter)
{
if (ModelState.IsValid)
{
db.Newsletters.Add(newsletter);
db.SaveChanges();
if (Request.IsAjaxRequest())
return PartialView("SimpleMessage");
else
return View("SimpleMessage")
}
if (Request.IsAjaxRequest())
return PartialView(newsletter);
else
return View(newsletter);
}

Related

Get Query String Value in ASP.NET MVC

I have this URL
var url = "/test/Create/" + $("#hdnFlag").val() +"?CmpT="+"Ilim";
window.location.href = url;
and in my Test controller I do this to get query string value
tM_PMO.Type = Request.QueryString["CmpT"];
But always give me null values.
There is a difference between the GET and POST types.
Query string can be read with the URL of the GET request. However, you cannot read the Query string value in the URL when you make a POST request. For this you need to submit it to the server.
Below I give you a few examples of usage.
GET Request
You can read Query string with URL as below
public ActionResult Test(string CmpT)
{
if (!string.IsNullOrWhiteSpace(CmpT))
{
//your codes...
}else
{ }
return View();
}
POST Request
If you are making a POST request and trying to read from the URL, it will return null. In order to read it, you need to send this value to the server as follows.
1st way : In your Html.BeginForm in your View Below, submit Query string as below and read this value as Action parameter
View Page
#using (Html.BeginForm("Test", "XController", new { returnUrl = Request.QueryString["CmpT"] }, FormMethod.Post, new { role = "form" }))
{
<button type="submit">Send</button>
}
Controller
public ActionResult Test(string returnUrl)
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//your codes...
}else
{ }
return View();
}
2nd way : Create a hidden form element as part of the form between the Html.BeginForm tags in your view page and give its value as a query string. Then call it in Action method like below.
View Page
#using (Html.BeginForm("Test", "XController", FormMethod.Post, new { role = "form" }))
{
#Html.Hidden("returnUrl", Request.QueryString["CmpT"])
<button type="submit">Send</button>
}
Controller
public ActionResult Test(string returnUrl)
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//your codes...
}else
{ }
return View();
}
or for multiple form items (You can also access other form elements this way)
public ActionResult Test(FormCollection fc)
{
string _returnUrl = fc["returnUrl"];
if (!string.IsNullOrWhiteSpace(_returnUrl))
{
//your codes...
}else
{ }
return View();
}
I hope you are looking for below code sample where we just fetch the value in url which we says query string:
Request.QueryString["querystringparamname"].ToString();
You can assign this in any Var and use accordingly.

How can I return javascript from a controller actionresult using ContentResult?

I'm wondering how I can return a javascript alert when the file that usually gets generated is not created in the folder. When the else statement is ran, it returns the literal text at the top of the browser tab instead of the alert that I am looking for. It looks like this:
Code:
public ActionResult DownloadFile(string path, string fileName)
{
if (System.IO.File.Exists(path))
{
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
return File(fileBytes, "application/force-download", fileName);
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('No data was found to create a CSV file!');</script>");
}
}
Firstly you can use the method public virtual ContentResult Content(string content, string contentType); rather than public virtual ContentResult Content(string content);
Controller:
public ActionResult DownloadFile()
{
return Content("alert('No data was found to create a CSV file!');", "application/javascript");
}
In addition,you can also write a result which has a Parametrical constructor and extends ContentResult.You can refer to it
Here is a demo worked:
Controller:
public ActionResult DownloadFile()
{
//return Content("alert('No data was found to create a CSV file!');", "application/javascript");
return new JavaScriptResult("alert('No data was found to create a CSV file!');");
}
public ActionResult DownloadFile1() {
return View();
}
public class JavaScriptResult : ContentResult
{
public JavaScriptResult(string script)
{
this.Content = script;
this.ContentType = "application/javascript";
}
}
DownloadFile1:
#{
ViewData["Title"] = "DownLoadFile1";
}
<h1>DownLoadFile1</h1>
<div>
<partial name="DownLoadFile" />
</div>
#section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$.getScript("/Test/DownloadFile");
});
</script>
}
Result:

Redirect Json error when no json is being parsed

I am trying to redirect from a controller action to another controller action.
Even though the debugger steps inside the second Controller Action and appears to render it ,and even in the Browser -response section the page appears rendered and its status is 200 ok i get:
Error:SyntaxError: Unexpected token < in JSON at position 0
And the page does not change.
The code:
LocationController
[HttpPost, ActionName("Attach")]
public IActionResult Attach([FromBody]List<Location> locations)
{
Story targetStory=TempData.Get<Story>("tstory");
if(targetStory!=null && locations!=null)
{
var slocs=this.context.StoryLocations.Where(sloc=>sloc.StoryId==targetStory.Id);
this.context.RemoveRange(slocs);
this.context.SaveChanges();
foreach(Location loc in locations)
{
this.context.StoryLocations.Add(new StoryLocation{LocationId=loc.Id,StoryId=targetStory.Id});
}
this.context.SaveChanges();
}
return RedirectToAction("Index","Story");
}
Story Controller
[HttpGet]
public string Test()
{
return test;
}
[HttpGet]
public IActionResult Index()
{
TempData.Clear();
List<Story>Stories=this.context.Stories.ToList();
return View(this.context.Stories);
}
I have tried to redirect to different actions from the second controller and the request is made and it is ok (status 200 green) but it wont change the view even though the chrome-response from "Story/Index" is ok.

Auto update a table on button click

I have a table in a page. I want to update / reload the table continuously on a button click for every 5 seconds.
The table gets the values from the query running in the model and I don't want duplicate values to be put in the table again.
I also want to stop the reloading of the table on when I click on a another button which is the stop button.
How can I do it? Thanks!
When you click on first button set interval function, which will execute your updating script. And click on other button will clear this interval.
// Click on first button
var flag = setInterval(func, 5000);
// Click on second button
clearInterval(flag);
where func is your updating function
Try that if possible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using bhanu1.Models;
namespace bhanu1.Controllers
{
public class ranuController : Controller
{
//
// GET: /ranu/
private personEntities1 per = new personEntities1();
public ActionResult Index()
{
return View(per.sandeep1.ToList());
}
//
// GET: /ranu/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /ranu/Create
public ActionResult Create()
{
return View();
}
//
// POST: /ranu/Create
[HttpPost]
public ActionResult Create([Bind(Exclude = "Id")]sandeep1 san)
{
try
{
// TODO: Add insert logic here
per.AddTosandeep1(san);
per.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ranu/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /ranu/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ranu/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /ranu/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}

How to stop an MVC RedirectToRouteResult JavaScript?

I am designing a site and am trying to be compatible with javascript turned off or on.
I have a Controller Action named as follows...
public RedirectToRouteResult AddWorkAssignment(int id)
{
// delegate the work to add the work assignment...
return RedirectToAction("Index", "Assignment");
}
and my jQuery I do a post
$('#someButton').click(function() {
var id = $('#whereTheIDIs').val();
$.post('/Assignment/AddWorkAssignment/' + id);
return false;
});
but the RedirectToAction on the controller will do just that.... how do I stop the redirect to occur, or how do I structure the controller and page to handle this, because I want the redirect to occur if javascript is turned off.
Change your controller to something like this:
public ActionResult AddWorkAssignment(int id)
{
// do work to add the work assignment....
if (Request.IsAjaxRequest())
return Json(true);
return RedirectToAction("Index", "Assignment");
}
You could create your own filter attribute too... much like the AcceptVerbs attribute.
HTHs
Charles
EDIT: AjaxRequest ActionMethodSelectorAttribute attribute
Kickstart from here
public class AjaxRequest : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
return controllerContext.HttpContext.Request.IsAjaxRequest();
}
}
Then your controller:
public RedirectToRouteResult AddWorkAssignment(int id)
{
// do work to add the work assignment....
return RedirectToAction("Index", "Assignment");
}
[AjaxRequest]
public JsonResult AddWorkAssignment(int id)
{
// do work to add the work assignment....
return Json(true);
}

Categories

Resources