I have a controller create and return content where it triggers an alert.
The problem it load an empty page. How can I prevent it to load an empty page and stays in the current view and do nothing just pop the alert.
What I really wanted here is before the user can create new data, it will validate first if the diseaseID is already existing for specific assessmentID, and when the result is null, it will just pop an alert and do nothing. But here I'm just trying make alert() work properly.
Controller:
public ActionResult CreateDisease(int? diseaseID,int? assessmentID, DiseaseList diseaselist)
{
diseaselist.DiseaseID = diseaseID;
diseaselist.AssessmentID = assessmentID;
db.DiseaseLists.Add(diseaselist);
db.SaveChanges();
return Content("<script language='javascript' type='text/javascript'>alert('Item already exist');</script>");
}
You dont need to return the script as content from the controller, just return the values as json that will tell you that the item already exist and based on that true or false value show an alert from the client side js.
your controller code will look something like this
diseaseModel.DiseaseID = diseaseID;
diseaseModel.AssessmentID = assessmentID;
diseaseModel.AlreadyExist = true;
return Json(diseaseModel);
Related
Hi have a scenario where in i have 3 views in the first view i have some textbox and then next button on click of next button the second view will be shown and the second view will also have some textbox and next button the third view is the final view which has few textboxes and submit/finish button. On click of submit/finish button all the data from view1,view2 and view3 should be saved to database. How to achieved it using ASP.NET MVC
You can use temp-data and their keep method to persist data in subsequent request.
Just keep all required field data into temp-data and get all this in one object(temp-data) and save them
Here is an eg. for it:
public ActionResult Add(Model model)
{
if(ModelState.IsValid)
{
db.Model.Add(model);
db.SaveChanges();
return RedirectToAction("Add2");
}
return View(model);
}
it redirects to the second view or a partial view, and the same with the 2nd to the 3rd. Hope it helps.
if you want to pass data from one view to another view then you can use TempData
ex.
TempData["Key"] = "test";
and can get value from tempdata like
#{
var abc = TempData["Key"];
}
Note: You can get tempdata value to next action after that it will be destroy.
This is one of method inside my controller.
[HttpPost]
public JsonResult Ajax(string AJAXParameter1)
{
List<string> data = new List<string>();
data.Add("AJAXParameter1=" + AJAXParameter1);
return Json(new { data, result = "OK" });
}
If parameter AJAXParameter1 recieves value as passport i want to display view that contains fileds related to passport. If it recieves value as pan i want to render some different view that allow us to add pan card related details. For pan and passport i have models. Based on Id i want to generate view.
I believe the best way to do this is to simply create two views or partialviews based on how your application will have to look, one for the passport and one for the pan card.
Then in your controller method see which one you receive and return the view needed.
something like:
[HttpPost] public ActionResult ReturnNeeded(string Parameter1){
if (IsPassport(Parameter1)){
return View("PasswordView");
}else if (IsPan(Parameter1)){
return View("PanView");
}
return View("OopsBadRequest");
}
maybe?
Session variable lost after a controller calls another View to render.
public ActionResult Index(Customer model, string cancel, string effective)
{
if(!string.IsNullOrEmpty(cancel))
{
//update database
Session["variable2"] = new Info(){ Text = "Do not processed"};
return View("Cancelation"); //error stated occurs when calling another view
}
if(!string.IsNullOrEmpty(effective)
{
//do data base update
Session["variable1"] = new Info(){ Text = "Processed"};
return View(model); //All good here
}
{
I have a MVC controller that when post back to it I set a Session variable "variable1", then I do return View(model). In this case all is good I can access the new Session variable1 everywhere.
But when I post back to the same controller again, I check the button clicked and then I set another Session variable, "variable2" this time I do return View("Cancelation").
This last variable2 is lost and does not show on HttpContext.Current.Session["variable2"] anywhere in the application.
Can someone help to understand why?
What I found was that because I was using SQL Server as Session store, I had to use Serialize() attribute on the object, then it worked.
Say the requirement is to redirect to another page after successfully saving a model in an ASP.NET MVC controller:
[HttpPost]
public ActionResult Index(ViewModel viewModel)
{
if (ModelState.IsValid)
{
// Do save;
return RedirectToAction("whatever"); // <--- here's the problem
}
// display validation errors and so
return View(viewModel);
}
This would work fine unless the controller was rendered as a Child Action:
#{
Layout = "my layout";
Html.RenderAction("something else, a view for example");
Html.RenderAction("Index action of the above controller"); // <----
}
In this case RedirectResult class would check and see that the context is a child action and would throw the exception: "Child actions are not allowed to perform redirect actions".
I understand that writing to Response stream is already in progress and a redirect cannot take place here but nevertheless one has to be able to redirect to other pages after a server-side action in a controller even if that action is a child action. We use Layouts and RenderActions to reuse the shared parts of the page design.
How would you implement such a redirect in such a controller?
Edit:
The main goal is to reuse View/Controllers that do a specific job and split them to logical concepts like displaying some data or providing an edit form. My approach here is to use RenderAction to render their result into a container. Container view (main page's Index action) acts as a traditional asp.net Page, its Layout view as a Master page and edit and view controller/views are equivalent to User Controls (modules). The problem is there is no way to Redirect the Response after something has been written to it:
I'll submit a new answer in an attempt to keep things clean.
A normal mvc flow goes like this :
Http command reaches 1 controller which acts as a choirmaster(aka controller) and calls several logic containers(e.g services / commandHandlers) :
public ActionResult Index(){
var data = _yourService.FetchData();
return View(data);
}
This controller renders 1 view which can have multiple partials
#{
Layout = "my layout";
}
<p>Some html</p>
Html.RenderPartial("A shared partial");
Html.RenderPartial("shared\yourUserControl", Model.PropertyOrSomething);
If the partial contains too much logic to generate you could add a RenderAction or create an htmlHelper extension.
But neither of these should be able to control the flow of your request, a save or something that can redirect should in my opinion never be called from inside a view.
I assume you want to reuse the code in your controller so badly because it is getting quite big.
My advice would be to try and clear that controller up as much as possible by delegating as much of the logic upwards as you can.
Just by looking at your controller method for 5 seconds you should get an idea of what this action will do, if that's not the case : refactor it ! :)
If i understand correctly you have a parent controller which accepts a saveAction and while rendering the view you call another(?) saveAction as a child.
This flow feels unnatural to me. The parent action and only the parent action should handle the save command. You can render as many child actions as you want as long as they are only used to render some html(as this is what the view does). Don't let them handle redirection or saving, that way of working is everything but transparant for colleges or future you.
The controller controls the flow, not the view.
Edit:
A normal setup would be having 2 actions, eg: Index and Put.
public ActionResult Index(){
//fill model with dropdown data etc
return View();
}
public ActionResult Put(viewModel data){
if (ModelState.IsValid)
{
// Do save;
return RedirectToAction("whatever"); // <--- here's the problem
}
// display validation errors and so
return View("Index",viewModel);
}
Edit2:
If you return View("Index",viewModel) you will generate your index view with it's layout and the validation messages will be located in the modelstate.
Your view however should only have 1 childaction(or more if there are multiple, as long as it's not the save action).
Your Index view could look like this :
#{
Layout = "my layout";
}
Html.RenderAction("something else, a view for example");
#Html.BeginForm("Put","YourController"){
//all your input controls which will also show the validation errors
}
Edit 3:
If you want to reuse html code you should use #Html.Partial or Html helper extension methods. Note that if you pass no model the parents model is passed but you can pass a submodel to match the type safety of the partial.
It would look something like this :
#{
Layout = "my layout";
}
Html.RenderAction("something else, a view for example");
Html.RenderPartial("shared\yourUserControl", Model.PropertyOrSomething);
Try using AJAX in your view to do this, and instead of returning a RedirectToAction in your controller, return a JSON object:
View:
$.ajax({
url: '<%: Html.ResolveUrl("~/ControllerFolder/ControllerName/") %>',
type: "POST",
data: data,
success: function (result) {
$("#Div").html(result);
if (result.redirectUrl != null)
{
window.location = result.redirectUrl;
}
}
});
Controller:
[HttpPost]
public ActionResult Index(ViewModel viewModel)
{
if (ModelState.IsValid)
{
// Do save;
return Json(new { redirectUrl = Url.Action("NewAction", "NewController", RouteValues)});
}
// display validation errors and so
return View(viewModel);
}
Hope this helps...
Trying to build some simple app with rikulo framework and have a question:
Is it possible to find View inside hierarchical layout ? and how ? (in Dart)
There's some documentation on Rikulo site about IdSpace but I didn't quite understand how to use it. Should I extend View with IdSpace ? Or View will auto-generate the Id ?
Update (add code example)
/*
* Function will actualy build View
*/
void _buildUi(Element tagElement)
{
View mainView = new View();
mainView.profile.width = '100%';
mainView.profile.height = '100%';
mainView.layout.type = 'linear';
mainView.layout.orient = 'vertical';
mainView.style.cssText = "background: yellow;";
View vWorkSpace = new View();
vWorkSpace.profile.width = 'flex';
vWorkSpace.profile.height = 'flex';
vWorkSpace.layout.type = 'linear';
vWorkSpace.layout.orient = 'horizontal';
vWorkSpace.style.cssText = "background: red;";
//
// Left menu
View vLeftBar = new View();
vLeftBar.profile.width = "10%";
vLeftBar.profile.height = "10%";
vLeftBar.layout.type = 'linear';
vLeftBar.layout.orient = 'vertical';
vLeftBar.layout.spacing = '10';
View vLogo = new View();
vLogo.addChild(new Image('images/google_chrome.png'));
vLeftBar.addChild(vLogo);
Button vButton = new Button();
vButton.text = 'Sign in with Google';
vLeftBar.addChild(vButton);
vButton.on.click.add((e){ // Somehow I get an error here: Method 'add' not defined for class 'Stream'
broadcaster.send(new ViewEvent('foo'));
});
vWorkSpace.addChild(vLeftBar);
mainView.addChild(vWorkSpace);
mainView.addToDocument(ref: tagElement, layout: true);
}
In another place in dart.app when handling the vButton click event. How I could find (in code) the vLogo View ?
The easiest way to retrieve a View in the code is to give it an id:
View vLogo = new View();
vLogo.id = "vLogo";
Then, in your event listener, use query to access it:
button.query("#vLogo"); // returns vLogo
However, in your case, you will be able to directly access the vLogo instance within the event listener closure.
Sure, like Element, View provides CSS selector based retrieval called query and queryAll. You can use them to retrieve the view as you retrieve the DOM elements.
In general, you don't have to worry about IDSpace, unless you want to use the same ID in different views. A hierarchy tree itself is an ID space. If a view implements IDSpace, it forms another ID space.