Multiple actions on the same view/controller in ASP.NET MVC - asp.net-mvc

First of all I want to ask for my bad English. I'm very new to ASP.NET MVC and currently writing my first web app.
I have a controller like this:
namespace MaterialProject.Controllers
{
public class AdminController : Controller
{
[HttpGet]
public IActionResult Admin()
{
//file some Viewbags from database
}
[HttpPost("UpdatePassword")]
[ValidateAntiForgeryToken]
public IActionResult UpdatePassword(EditUser euModel)
{
//database update
}
[HttpPost("UpdateGroupID")]
[ValidateAntiForgeryToken]
public IActionResult UpdateGroupID(EditUser euModel)
{
//database update
}
}
}
and I want my view to have 2 submit buttons when the user will choose UpdatePassword I want to execute that action and the user choose UpdateGroupID to execute the other action.
My view called Admin.chtml
<div class="container">
<form asp-controller="Admin" asp-action="UpdatePassword" method="post" class="form-horizontal" role="form">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<label asp-for="Username" class="control-label" value=""></label>
<select asp-for="ID" class="form-control"
asp-items="#(new SelectList(ViewBag.editUser, "ID", "Username"))"></select>
</div>
<div id="submit">
<input type="submit" name="submit" value="Update Password" />
</div>
</form>
<form asp-controller="Admin" asp-action="UpdateGroupID" method="post" class="form-horizontal" role="form">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<label asp-for="Username" class="control-label" value=""></label>
<select asp-for="ID" class="form-control"
asp-items="#(new SelectList(ViewBag.editUser, "ID", "Username"))"></select>
</div>
<div id="submit">
<input type="submit" name="submit" value="Update GroupID" />
</div>
</form>
</div>
If I execute the above code I get this error:
An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'UpdatePassword' was not found. The following locations were searched:
/Views/Admin/UpdatePassword.cshtml
/Views/Shared/UpdatePassword.cshtml
/Pages/Shared/UpdatePassword.cshtml
Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable originalLocations)
Because I have never created that view.
Is there any way by pressing any from the submit buttons on my form to call different blocks of code from my controller?
Thanks in advance for your help.

Without seeing the full content of those actions, it's hard to say, but I'd guess based upon that error message you have return View(); near the bottom of both of your post actions. Most likely your code inside of both of the posts is actually running, it just doesn't know what to do at the end.
You have several options.
Create views for those actions with the same name
Modify the return View(); to something like return View("Admin"); so it returns the admin view
Change it to a redirect...ex. return RedirectToAction("controller","view");

Related

file uploding action not get invoke

I'm working on ASP.Net MVC project using Visual Studio 2017 . When i click File upload button it not direct to controller method it directs to a blank page .This page worked as expected Few hours ago nothing changed ,but now im getting this issue Browser console gives me this error .
The character encoding of the plain text document was not declared.
The document will render with garbled text in some browser
configurations if the document contains characters from outside the
US-ASCII range. The character encoding of the file needs to be
declared in the transfer protocol or file needs to use a byte order
mark as an encoding signature
.
View code
#using Microsoft.AspNetCore.Mvc.Localization
#inject IViewLocalizer Localizer
<div class="box">
<div class="box-header">
<h3 class="box-title">#Localizer["ImportWorkFile"]</h3>
<h1>#ViewBag.message</h1>
<form action="#Url.Action("ImportWorkers")" method="post" enctype="multipart/form-data">
<input type="hidden" name="OrganizationId" value="#Model"/>
<input type="hidden" name="send" value="true" />
<div class="form-horizontal">
<div>#Localizer["Only"] <strong>.csv</strong> #Localizer["FileSuported"]</div>
<div class="form-group">
<label for="importFile" class="col-md-2 control-label"></label>
<div class="col-md-12">
<input id="importFile" name="csvFile" type="file" class="form-control" required />
</div>
</div>
<input type="submit" name="name" value="#Localizer["Send"]" />
</div>
</form>
</div>
</div>
Controller Method
[HttpPost]
public ActionResult ImportWorkers(bool send, long OrganizationId)
{
}

i want to get the form data form one gsp and want to access that data in another gsp and want to insert that data in table, how can i do this?

This is one gsp where i created one form
<div class="form-group">
<label for="msg_to">To</label>
<input type="email" id="msg_to" name="msg_to" class="form-control" style="width:500px;" required="">
</div>
<div class="form-group">
<label for="msg_subject">Subject</label>
<input type="text" id="msg_subject" class="form-control" style="width:500px;"name="msg_subject" required="" maxlength="50">
</div>
<div class="form-group">
<label for="msg_body">Body</label>
<textarea class="form-control" id="msg_body" style="width: 500px; height: 250px" name="msg_body" required="" ></textarea>
</div>
%{--<button type="submit" class="btn btn-default">Send</button>--}%
<g:actionSubmit value="Send" action="g_Inbox" style="color: #000000"></g:actionSubmit>
</form>
The data of above form must be access to another controller after submit and data should be display in the table form on that another view.
I fetch above data in following action:
def g_Inbox(){
def msg_to = params.msg_to;
def msg_subject = params.msg_subject;
def msg_body = params.msg_body;
println msg_to
println msg_subject
println msg_body
render(view: 'g_Inbox', model: [m_to : msg_to , m_sub : msg_subject , m_body: msg_body] )
}
from here i want to send it to view and want to add in new row of table..
You're in luck. What you want to do is very easy with Grails. But... you have to do your homework.
Things to read and digest
(best served with pizza and iced tea)
Groovy Server Pages -
https://grails.github.io/grails-doc/latest/guide/theWebLayer.html#gsp
Controllers - https://grails.github.io/grails-doc/latest/guide/theWebLayer.html#controllers
Once you understand GSP and controllers, you'll know exactly what to do.
Simple if You know how it works
render(view: 'g_Inbox', model:[params:params])
Access the params in gsp by
${params.msg_to}
and for Another Controller
redirect controller:'Controller' action: 'create',params:params

Login MVC redirect to another page

I have a log-in page. When the user hits the log-in button the button will calla another action method. that action method will have two parameter. the user provided userid and password. then it do some validation and redirect to another action method according to the outcome. I am struggling with there. i guess this is pretty simple. i am new to MVC. Any help would be appriciated.
View
<div class="container-fluid">
<div class="starter-template">
<h1>Policy Assessment Tool</h1>
<p class="lead">Are You Following Right?</p>
<button type="button" class="btn btn-primary btn-lg" onclick="location.href='#Url.Action("Create","UserDatas")'">Register for a An Account</button>
<h3><strong>OR</strong></h3>
</div>
<div class="row">
<form class="form-signin" role="form" method="post">
<div class="col-lg-4"></div>
<div class="col-lg-4">
<h2 class="form-signin-heading">Please Sign-In to Continue</h2>
<div class="input-group">
<input type="text" name="input_domain_id" class="form-control text-center" placeholder="Domain ID" autofocus required>
<input type="password" name="input_domain_password" class="form-control text-center" placeholder="Domain Password" required>
<div class="col-lg-12">
<p><button class="btn btn-lg btn-primary btn-block" type="submit" onclick="location.href='#Url.Action("Verify_Login", "Ldap_Login_Verify")'">Login</button></p>
</div>
</div><!-- /input-group -->
</div><!-- /.col-lg-4 -->
<div class="col-lg-4"></div>
</form>
</div><!-- /.row -->
</div>
Controller
[HttpPost]
public ActionResult Verify_Login(string input_domain_id, string input_domain_password)
//Log-in Logic
return View("Success")
Instead of using form tag use Html.BeginForm HtmlHelper and pass Model from Controller to View for the best practice. Here is link for you to get Getting Started With MVC5.
Based on the mark up above you need not worry about it, When the form is posted the values will get bound to the parameters of the action method, As the parameter names are similar to the form field names.
The above concept is called model binding. The below two links should give you a good idea on the same.
http://www.codeproject.com/Articles/710776/Introduction-to-ASP-NET-MVC-Model-Binding-An-Absol
http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx
I have tried to compile a simple example below.
Lets assume there is a view like below.
#model string
#{
ViewBag.Title = "Injection";
}
<h2>Injection</h2>
#using(Html.BeginForm())
{
<div id="formDetails">
#Html.TextBox("UserName")
</div>
<div>
<input type="submit" id="btnTest" value="Click Me" />
</div>
}
The Action method for the same would be like
[HttpPost]
public ActionResult Injection(string UserName)
{
return View("Injection");
}
So when i click on the submit button, The form is posted , Since the ViewName is injection, and there is a corresponding action method called injection it will automatically hit that action method. Since the parameter name of the method and field is the same, What ever value is there in the username textbox will get automatically bound to the method parameter.

Multiple Submit buttons in Form neither appearing in FormCollection of ASP.Net MVC Method

I'm at my wits end here...I have the following razor markup for my form:
<input class="k-button" type="submit" value="Post" name="SubmitButton" />
<input class="k-button" type="submit" value="Save" name="SubmitButton" />
The problem I'm experiencing is that the FormCollection parameter of the controller action method does not include SubmitButton in its Key/Value pairs.
I've come across this post here that seems to have had the same problem. The solution seemed to be to use a ActionMethodSelectorAttribute AND to remove the use of [Remote] validation. But I really need my [Remote] validator though, so it is not an option for me to remove that. Is there no other solution, or is this some bug I just have to deal with?
I'm thinking along the lines of having to replace my use of two buttons with a single Save button, and then add a "Post" checkbox. Then in the controller action I check for the presence of the Post KeyValue pair. But this is less than idea. I prefer the use of two buttons.
EDIT: more view markup following Igor's request:
#using (Html.BeginForm())
{
#Html.ValidationSummary(false)
<fieldset>
<legend>Edit details for Client Warehouse Request </legend>
#Html.HiddenFor(model => model.ModelObject.CustomerCode)
#Html.HiddenFor(model => model.ModelObject.ReqNr)
<div style="table-layout: initial;">
<div class="columnDivider">
<div class="editor-label">
#Html.LabelFor(model => model.ModelObject.ReqNr)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.ModelObject.ReqNr)
</div>
<div class="clear">
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ModelObject.CreationDate)
</div>
... many other fields following the above structure...
<input class="k-button" type="submit" value="Post" name="SubmitButton" />
<input class="k-button" type="submit" value="Save" name="SubmitButton" />
</div>
<div class="columnDivider">
...some more fields
</div>
<div>
Here I have a Kendo UI datagrid that gets submitted with the form
</div>
</fieldset>
}
Try:
<input type="hidden" name="SubmitButtonValue" id="SubmitButtonValue" />
<input class="k-button" type="submit" value="Post" name="SubmitButton" />
<input class="k-button" type="submit" value="Save" name="SubmitButton" />
<script type="text/javascript">
$(document).ready(function(){
$(".k-button").click(function(){
$("#SubmitButtonValue").val($(this).val());
});
});
</script>
and check for "SubmitButtonValue" key in FormCollection.

asp mvc user controls

I want to write user control to sending email.
I write that control:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<form action="" method="post">
<div class="box">
<div class="box-header">
Rejestracja</div>
<div class="box-content">
<div>
Imię
</div>
<div>
<input name="firstname" type="text" />
</div>
<div>
Nazwisko
</div>
<div>
<input name="lastname" type="text" />
</div>
<div>
Email
</div>
<div>
<input name="email" type="text" />
</div>
<div>
Ulica nr domu mieszkania
</div>
<div>
<input name="street" type="text" />
</div>
</div>
<div class="box-info">
Wypełnij formularz rejestracyjny i dołącz do klubu Oriflame.
</div>
</div>
<div style="clear: both;">
</div>
</form>
And i put this control in masterpage:
<% Html.RenderPartial("Kontakt"); %>
That control named :kontakt.aspx" and it is in shared folder
My question is where i must write code with sending email. What action i myst set in controls form.
This control was be on all sites.
Regards
The form needs to post to a URL that is setup to route to a controller action. That could be the current page's Url or a different Url.
In your controller you want a method that accepts the form fields. This could be a FormCollection object or a strongly typed model who's properties map to the form names.
[HttpPost]
public ActionResult Foo(FormCollection form)
{
.. use the form collection to construct your email ...
}
If you're using a strongly typed view, rather than building the HTML inputs yourself you could do:
<%= Html.TextBoxFor(x => x.FirstName) %>
And in your controller action you can use the model rather than the FormCollection:
[HttpPost]
public ActionResult Foo(KontaktModel details)
{
.. use the details object to construct your email ...
}
I suggest taking a look through the tutorials at http://asp.net/mvc as well as doing the NerdDinner tutorial.
You have to create some sort of Controller that will receive form data. And you can send those emails from the server (from controller or whatever you chose to send it).
Write your email creation and sending code in a controller method. You'd then call it from this Kontakt partial view like this:
<% using (Html.BeginForm("SendMail", "Mail")) { %>
Where SendMail is the method, and Mail is the name of the controller.
public ActionResult SendMail()
{
//build your mail objects and send as needed.
return View();
}

Resources