Using MVC i want to change the view from the controller - asp.net-mvc

I have done some reading and I can't figure out how I change the view, by using the controller to handle the changing of the view. I have 2 buttons that currently use onclick to change the view but I want it done via the controller.
This is my view:
#{
ViewData["Title"] = "RoleCreator";
}
<div class="ui-layout-center">
<h1>Example Header</h1>
<p>Example Text </p>
<input type="button" value="Create Role" onclick="location.href = 'RoleManager/RoleCreator'"/>
<input type="button" value="Edit Role" onclick="location.href='RoleManager/RoleEditor'"/>
</div>

You can use conditions to send different views . give name property to buttons.
On controller side you can call action as per name
[HttpPost]
[ActionName("IndexPost")]
[Button(ButtonName = "Command")]
public ActionResult GetFareFamilies()
{
return View("View1");
}
[HttpPost]
[ActionName("IndexPost")]
[Button(ButtonName = "Save")]
public ActionResult Save(AirPricingWithoutPNRViewModel pricingVm, PricingCommercialDetails commercials)
{
return RedirectToAction("Action name");
}

You can't change the view using the controller. To understand more about the MVC refer to this link and check the relationship between Model-View-Controller.
https://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx
To answer your question you may want to read more about partial views and ajax.
https://www.codeproject.com/articles/698246/asp-net-mvc-special-views-partial-view-and-layout
Using Ajax to render MVC View

Related

Pass Value of TextArea to Controller

I have the following code in a Partial View that is Rendered inside of another Partial View that is used as the _layout for all views in the project. There is a textarea for comments. I need to get the value of the Textarea to the Action Method in my controller. There is no ViewModel, so I don't know how to capture the contents.
<header>
<h4> Application Notes </h4>
#using (#Html.BeginForm("Comment", "LoanApplication"))
{
#Html.TextArea("Comment")
#*<textarea cols="100" rows="2" name="Comment" placeholder="Leave Comment ..."></textarea>*#
<input value="Add Comment" type="submit" />
}
</header>
The controller code is :
[HttpPost]
[Route("Comment")]
public async Task<ActionResult> Comment(string comment)
{
var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;
var applicationComment = new LoanApplicationComment
{
};
await loanApplicationServiceProxy.PutLoanApplicationCommentAsync(applicationComment);
return View();
}
It seems as if it should be something easy, but I can't seem to figure it out. Thanks for any and all assistance.
Change
string comment
To
string Comment
One other thing to try is to receive a FormCollection instead.

Is it possible to prevent parent view from reloading

I have two views, one master to the other. There are certain cases when I need the parent view to stay the same while the child view reloads. Is AJAX the only option, or is there another way of doing this?
P.S. Even with the only option being AJAX I'd really appreciate if someone could show the steps to take in ASP.NET MVC.
Yes, only an Ajax call will prevent you from loading the whole page.
Let's say this is your page scheme:
<div id="master">
<div id="section1">
// use render partial to render this
</div>
<div id="section2">
// use render partial to render this
</div>
</div>
In order to reload a section you can use JQuery.load to reload only it:
$("#section2").load('#Url.Action("Action", "Controller")');
Using Ajax forms is a way I like to do something similar as you can use the UpdateTargetId to render your partial view, and you can easily use the AntiForgeryToken features
View:
<div>
#using (Ajax.BeginForm("MyAction", new { id = #Model.MyData }, new AjaxOptions
{
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "renderView"
}))
{
#Html.AntiForgeryToken()
<input type="submit" name="submit" value="Submit" />
}
</div>
// This will get populated with the partial
<div id="renderView" />
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> MyAction(int id)
{
var output = new MyModel{ .....};
return PartialView(output);
}

Using webforms in MVC

I am learning MVC, following THIS tutorial. (link will take you directly to where i'm stuck). so far I have learnt, there's a controller for every view. Now i have to take input from user through web entry form as mentioned in tutorial. In my project, i have a controller named Default1 and i can run it as localhost:xyz/Default1/Index. it runs perfect.
Then i created a new Controller, named Default2 and bound it to some view to display some data, and it worked perfect as localhost:xyz/Default2/Displaycustomer. the customer information was static (hard coded). and controller is as:
public ViewResult DisplayCustomers()
{
Customer cobj = new Customer();
cobj.Code = "12";
cobj.Name = "Zeeshan";
cobj.Amount = 7000;
return View("DisplayCustomers",cobj);
}
Now i have to take input from User, regarding cutomer iformation, using html page as mentioned in tutorial. so i tried adding a new webform under view folder, and and modified my controller as:
[HttpPost]
public ViewResult DisplayCustomers()
{
Customer cobj = new Customer();
cobj.Code = Request.Form["Id"].ToString();
cobj.Name = Request.Form["Name"].ToString();
cobj.Amount = Convert.ToDouble(Request.Form["Amount"].ToString());
return View("DisplayCustomers",cobj);
}
My Question is: How can i make my project stared, so that it takes input first, and then displays it, using above controller? Did i add the webform at right location? What would be the link to run it? i tried localhost:xyz/Default2/entryform etc. but failed.
(in my entryform.aspx, i have mentioned form action="DisplayCustomer" )
It sounds like what you're missing is an action to just display the form. In otherwords, you just need an action to display a form. That form's POST action should reference your controller's DisplayCustomers action.
So in your controller code:
public class CustomerController : Controller
{
[HttpGet]
public ViewResult New()
{
return View("NewCustomer"); //Our view that contains the new customer form.
}
// Add your code for displaying customers below
}
And in your view, you have code like this
#using(Html.BeginForm("DisplayCustomers", "Customer")) {
<!-- Add your form controls here -->
}
Notice that I'm using the version of the BeginForm helper that specifies the action method and controller to call. This will write the form tag to post back to your DisplayCustomers action. Here is the equivalent HTML:
<form method="POST" action="/Customer/DisplayCustomers">
You would then access your form using the URL http://test.server/Customer/New.
This may not be the best example in the world...but this will at least get you rolling..
url would be:localhost:1234/Home/Customer
the controller
public ActionResult Customer()
{
return View();
}
[HttpPost]
public ActionResult Customer(FormCollection frm)
{
var name = frm["name"].ToString();
var address = frm["address"].ToString();
ViewBag.Name = name;
ViewBag.Address = address;
return View();
}
The view
<div>
#using (Html.BeginForm())
{
<input type="text" name="name" id="name" />
<input type="text" name="address" id="address"/>
<input type="submit" name="submit" value="submit" />
<input type="text" name="namedisplay" value='#ViewBag.Name'/>
<input type="text" name="addressdisplay" value='#ViewBag.Address'/>
}
</div>

What to do if action button and form fields are in different sections?

Let's say we have an edit form to create a new user. Now the save button is placed in a different section, the footer.
My problem is that I can't get the edit fields and the save button in one form, because the button is in a different section.
Because of that, I can't submit the form.
What is the best approach to this problem?
_Layout.cshtml
<div class="content">
#RenderBody()
</div>
<div class="footer">
#RenderSection("Footer")
</div>
Index.cshtml
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Footer
{
<input type="submit" value="Save" />
}
#using(Html.BeginForm())
{
<h2>New User</h2>
#Html.EditorForModel()
}
You could call form.Dispose() explicitly, instead of the using statement:
#{ var form = Html.BeginForm() }
<h2>New User</h2>
#Html.EditorForModel()
#section Footer
{
<input type="submit" value="Save" />
#{ form.Dispose(); }
}
Edit
But you have to at least make sure the Body and Footer section are in the same container, for example:
<div class="content">
#RenderBody()
<div class="footer">
#RenderSection("Footer")
</div>
</div>
With the layout as written in the question, the content div (and therefore the form tag) must close before the submit button can ever appear. There's no way this can work logically:
<div class="content">
#RenderBody() ## form opens, and therefore must close here
</div>
<div class="footer">
#RenderSection("Footer") ## submit button is here -- can never be inside the form
</div>
Editorial aside: It seems like a very bad idea to have a form split across multiple partial views. You might call it a code smell -- I'd try to avoid it if possible.
You found a pretty awkward work around. I suggest doing it this way:
In order to distinguish actions of different buttons clicked, create a new property in your model: public string Action { get; set; }
Give you form an id and include a hidden input for your new model property.
<form id="my-form">
#Html.HiddenFor(x => x.Action)
...
</form>
Create buttons in the footer, with the same class, but different values:
<button class="btn-submit" value="action1">Submit</button>
<button class="btn-submit" value="action2">Submit</button>
Use the following JavaScript:
$('.btn-submit').live('click', function() {
// update value of hidden input inside the form
$('#Action').val($(this.val()));
// submit the form
$('#my-form').submit();
});
In your ActionResult perform different actions based on the value of Action property:
public ActionResult WahteverAction(WhateverModel model)
{
if(ModelState.IsValid)
{
if(model.Action == "action1")
{
// do whatever needs to be done for action1
}
if(model.Action == "action2")
{
// do whatever needs to be done for action2
}
}
return View();
}
I found a workaround for my problem. It's not nice, but it works.
I replaced the submit button with an anchor. When the anchor is clicked, a javascript function gets called.
<a name="save" onclick="submitAction(this)"></a>
The javascript function creates a hidden submit button in the form and clicks it.
function submitAction(sender) {
var action = $(sender).attr('name');
$('form').append('<input type="submit" style="display:none" id="tmpSubmit" />');
$('#tmpSubmit').attr('name', action);
$('#tmpSubmit').click();
}

Create reusable form contact component in asp.net mvc

I'm newbie at asp.net mvc, I'm trying to develop a reusable contact form component for asp.net mvc .
I have tryed to do it creating a PartialView with a form, I don't know if this is the better approach, for create a reusable component
My PartialView is
#model MyModel.ContactData
#using (Html.BeginForm("ContactForm", "ContactForm", FormMethod.Post)) {
<fieldset>
<p>
#Html.LabelFor(model => model.MailAddress)
#Html.EditorFor(model => model.MailAddress)
</p>
<p>
#Html.LabelFor(model => model.Message)
#Html.TextAreaFor(model => model.Message)
</p>
<input type="submit" value="Save" />
</fieldset>
}
The problems start with the controller, the controller is a specific controller for only this partialView.
public class ContactFormController : Controller
{
[HttpPost]
public ActionResult ContactForm(ContactData contactData)
{
if (ModelState.IsValid)
{
return PartialView("MessageSend");
}
return PartialView();
}
}
My problem is in case of some of the required fields are empty, in that case the controller returns only the partial view, not returning the partival view inside its parent context. I have tryed calling the PartialView from parent View as #Html.Partial, #Html.RenderAction, #Html.RenderPartial and the same occurs.
How can I return the partial view Inside it's parent Context? I have tried with
return View(ParentViewsName, contactData) but I dislike it because on form submitting it changes the url on address bar from /Contact to /ContactForm/ContactForm.
Perphaps I'm trying to create a reusable component with a wrong approach? It's better to update with ajax only the PartialView? Alternatives?
Thanks
From my understanding, you wish to display status message which is a partial view after user successfully submits the form. I think tempdata will be apt for this kind of situation.
public class ContactFormController : Controller
{
[HttpPost]
public ActionResult ContactForm(ContactData contactData)
{
if (ModelState.IsValid)
{
TempData["success"] = true;
return RedirectToAction("parentpage");
}
return View(contactData);
}
}
In parent page, check whether TempData["success"] is null and display the partial view "MessageSend".
Finally as Sundeep explains I have done this with ajax like this example Partial ASP.NET MVC View submit.
Thanks for your help.

Resources