How to display an alert message from .cshtml view - asp.net mvc - c#

I have two action result one sending a string and another loading the view
public ActionResult getTheString()
{
string message = //doing some thing ;
myModel myModel = new myModel();
myModel.property1 = message ;
return loadView(myModel);
}
public ActionResult loadView(myModel model)
{
return view (model);
}
loadView.cshtml
#model project.Models.myModel
#{
if(Model.property1 !=" ")
{what to do to show it as alert }
}
Here I am getting the prperty like model.property1 if it has some thing show the alert with that string and then load, if message does not contain anything then simply load.
Not permitted to use TempData , ViewBag , ViewData.
Not permitted to use Script tag in view . it has to be in a seperate js file

You could check with some simple Razor syntax
#if(!string.IsNullOrEmpty(Model.Property1)) {
<script>alert("#Model.Property1");</script>
}

you can use javascript and give alert once page is loaded.
<script type="text/javascript">
window.load = function() {
#if(!string.IsNullOrEmpty(Model.Property1)) {
alert("blah blah");
}
}
</script>

Related

Execute a controller from view in ASP.NET MVC - Razor

I am trying to print the name of the user who executes my web app. It is written in MVC-Razor.
From the initial View, I would to execute the controller below:
[Authorize]
public ActionResult Check()
{
var check = new CheckAD();
var user = new User {Name = check.CheckSecurityWithAD()};
if (!string.IsNullOrEmpty(user.Name))
{
return View("Checked", user);
}
var errors = new ErrorsModel()
{
Messages = new List<string>(){"You don't have permission"}
};
return View("Error", errors);
}
This controller returns another view if the user is correctly authenticated:
#model UsersActivationWeb.Models.User
#{
ViewBag.Title = "Checked";
}
#{ <p> Logged come #Model.Name </p>};
How can I print the second view (I think it's a partial view) in the first one using the controller?
Thanks
Sounds to me like you need an Html.Action. This will run the controller code and display the view contents that are produced where you place the call.
Most likely you will need this overload, Html.Action(string actionName, string controllerName).
Assuming the controller is called CheckController. In your initial view call it like this
#Html.Action("Check","Check")
Since you don't want people navigating to the Check view you should give it a ChildActionOnly attribute so it looks like this
[Authorize]
[ChildActionOnly]
public ActionResult Check()
{
//rest of code
}
Finally you almost certainly don't want the layout contents to appear with the Checked view so change your Checked view to this
#model UsersActivationWeb.Models.User
#{
Layout = null;
}
#{ <p> Logged come #Model.Name </p>};
Since you are doing authorization logic in the Check action you might not need the Authorize attribute. I say that because with it a user not logged in will not get the error or their name. Maybe you want this though, I'd need to know more about your code to say for sure.
This way you will either get the name of the user or the errors as required.

nothing display in the second view in MVC c#

In my web site I'm getting data from xml in first controller action method and display as dropdown (html select and option).When a user selects an item in first dropdown, selected item sent to the next view's controller as a parameter using jquery $.post. I have keep breakpoints and see what is going on. Data trasfer is success until second view . But display nothing. I have attached screenshot of my break points and codes.
This is my controllers.
public ActionResult First()
{
//get the location data
var Loc = getData("Location", "", "", "");
List<FirstData> Ilc = new List<FirstData>();
foreach(var val in Loc)
{
Ilc.Add(new Firstdata
{
Destination = val
});
}
ViewBag.Loc = Ilc;
return View();
}
this is how I pass data from first view to second action controller method
<script type:"text/javascript">
$(document).ready(function() {
$("#chk a").addCIass("btn btn-default");
$("#chk a").click(function () {
var url = '#Url.Action("Check","Cruise")';
$.post(url, { LocNane: $("#desti").val() }, function (data) {
//alert("succes");
});
});
});
</script>
this is how my second controller gets pass data[I made a breakpoint here]
public ActionResult Check(string LocName)
{
string d = LocNane;
var Nan = getData('Location',"Name",d,"");
List<Seconddata> nf = new List<Seconddata>();
foreach (var val in Nam)
{
nf.Add(new Seconddata
{
Naneof = val
});
}
ViewBag.Nn = nf;
}
and this is my second view and display data in break point
<body>
<div>
#foreach( var item in #VieuBag.Nm)
{
<h3>one</h3>
}
</div>
</body>
I put "#item.Nameof" inside the header tags , but it didn't work. so just to chek I put one. after go through the loop nothing display.what's the wrong.please help me with this.
The problem here is the success handler of $.post does not append/insert the returned html in any element. You can do something like this in success handler where divId is element Id in page where you want to show the returned html.
$("#divId").append(data);

ASP.NET - accessing ViewBag in a View

I have a one page that uses Javascript to load several PartialViews. I am trying to access ViewBag in some Javascript but am having problems.
MyView:
<div>
<script>
var test = #ViewBag.test;
alert(test);
</script>
</div>
The controller which handles this view:
public PartialViewResult MyView()
{
ViewBag.test = "test";
return PartialView();
}
When I run it, the Javascript alert does not appear. I get a "Conditional compilation is turned off" highlight under the View's calling of ViewBag.
When your view is rendered, this is what is produced:
var test = test;
..that is obviously not valid javascript.
You need to enclose it in quotes:
var test = "#ViewBag.test";
Which produces:
var test = "test";
..valid Javascript.

Why isn't viewbag value passing back to the view?

straight forward question , can't seem to get my viewBag value to display in a view that the user is directed to after completing a form.
Please advise..thanks
My Index ActionResult simple returns model data..
public ActionResult Index()
{
var source = _repository.GetByUserID(_applicationUser.ID);
var model = new RefModel
{
test1 = source.test1,
};
return View(model);
}
My Get Edit" ActionResult , simply uses the same model data as Index.
My Post "Edit" ActionResult, assigns the new values if any to the model and redirects to the Index page, but Index page does not display ViewBag value ??
[HttpPost]
public ActionResult Edit(RefModell model)
{
if (ModelState.IsValid)
{
var source = _repository.GetByUserID(_applicationUser.ID);
if (source == null) return View(model);
source.test1 = model.test1;
_uow.SaveChanges();
#ViewBag.Message = "Profile Updated Successfully";
return RedirectToAction("Index");
}
return View(model);
}
And in my Index view...
#if(#ViewBag.Message != null)
{
<div>
<button type="button">#ViewBag.Message</button>
</div>
}
ViewBag only lives for the current request. In your case you are redirecting, so everything you might have stored in the ViewBag will die along wit the current request. Use ViewBag, only if you render a view, not if you intend to redirect.
Use TempData instead:
TempData["Message"] = "Profile Updated Successfully";
return RedirectToAction("Index");
and then in your view:
#if (TempData["Message"] != null)
{
<div>
<button type="button">#TempData["Message"]</button>
</div>
}
Behind the scenes, TempData will use Session but it will automatically evict the record once you read from it. So it's basically used for short-living, one-redirect persistence storage.
Alternatively you could pass it as query string parameter if you don't want to rely on sessions (which is probably what I would do).
RedirectToAction causes an HTTP 302 response, which makes the client make another call to the server and request a new page.
You should be returning a view instead of redirecting.
The RedirectToAction(msdn) instructs your browser to make a new request.
So your server will be called again but it will be a new request with a blank viewbag and all
You could do a sort of internal redirect by just calling the index method, this way the viewbag will still have its data.
Edit : you'll also have to modify your index method or your View(model) line will try to render the edit. Full code below
public ActionResult Index()
{
var source = _repository.GetByUserID(_applicationUser.ID);
var model = new RefModel
{
test1 = source.test1,
};
return View("Index",model);
}
[HttpPost]
public ActionResult Edit(RefModell model)
{
if (ModelState.IsValid)
{
var source = _repository.GetByUserID(_applicationUser.ID);
if (source == null) return View(model);
source.test1 = model.test1;
_uow.SaveChanges();
#ViewBag.Message = "Profile Updated Successfully";
return Index();
}
return View(model);
}
You can try this way also
Controller
public ActionResult Test()
{
ViewBag.controllerValue= "testvalue";
..................
}
View -
define top of razor page
#{string testvalue= (string)ViewBag.controllerValue;}
$(function () {
var val= '#testvalue';
});

Async loading inside cshtml page

It it possible to use Task (System.Threading) inside Razor??
What i'm trying to do is this: I have a table that I want to async fill.
Look at the code:
#{
Func<dynamic, object> preenche =
#<text>
<tr><td>oi1</td><td>oi2</td></tr>
</text>;
}
...
<tbody>
#Task.Factory.StartNew(() =>
{
foreach(Apontamento ap in Model.apontamentos)
{
preenche(ap);
}
})
</tbody>
The output is just this: System.Threading.Tasks.Task
Is it possible? Or I can just have what i'm trying to do using Ajax?
If you want the page to render and appear instantly and then have something happen later on (say an operation takes 5 seconds to complete) then you can get the page to update when the data is available by doing something like this (More information about .getJSON).
On your Razor view you can add some JavaScript:
<script type="text/javascript">
$.getJSON('LongRunningAsyncTask', function (result)
{
// Populate table or other actions with: result.Data
// ...
});
</script>
Then in your Controller you would have the tasks like this:
public JsonResult LongRunningAsyncTask()
{
// Show this is async and won't render straight away...
System.Threading.Thread.Sleep(5000);
// Build up our view model
var viewModel = new TestViewModel();
// Send back as a Json result
var result = new JsonResult();
result.Data = viewModel;
return Json(result, JsonRequestBehavior.AllowGet);
}
You should NOT do this in the View. Make asynchronous action but when you start rendering the view all the data should be ready.

Categories