asp mvc user controls - asp.net-mvc

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();
}

Related

Multiple actions on the same view/controller in 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");

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.

unable to display the validation messages from #Html.ValidationSummary() in MVC view

I have a fairly simple form created in a partial view and loading the form on a jquery dialog. The view is tightly bound to a model. When the user clicks on the submit button with out entering any inputs, I need to show the validation messages.
<div>
<form method="post" enctype="multipart/form-data" id="ssimForm" action="Home/ProcessUploadedFile"
onsubmit="return false;">
<div>
<h3>
Select the file to be uploaded :</h3>
<span>
<input type="file" name="UploadFileName" id="UploadFileName" /></span>
</div>
<div>
<h3>
Select the date range :</h3>
<span class="uslabel">From Date(MM/dd/yyyy): </span>
<input class="usdate" id="usfromdate" name="StartDate" type="date" />
<span class="uslabel">To Date(MM/dd/yyyy): </span>
<input class="usdate" id="ustodate" name="EndDate" type="date" />
</div>
<div>
<br />
<input type="submit" id="submitButton" name="submitButton" value="Process File" />
</div>
#Html.ValidationSummary()
<div class="message-success">
<span>#ViewBag.Confirmation</span>
</div>
<div class="message-error">
<span>#ViewBag.Error</span>
</div>
</form>
</div>
Now comes the actual problem. when I submit the form I am able to see the validationSummary object populated with the messages, but they are not getting rendered on the screen.
I am able to see the messages if I replace the content of the dialog with the response from the jquery ajax call, that fetches the entire view from the server side. I do not want to take this approach as I beleive this is not the correct way to return validation summary in MVC.
Am I missing something? Any help is appreciated.
I don't know why you don't have the #using (Html.BeginForm()) { } block.
Here is my blog post for a quick and easy way to set up Validation Summary + Unobtrusive Validation for MVC3+.
http://geekswithblogs.net/stun/archive/2011/01/28/aspnet-mvc-3-client-side-validation-summary-with-jquery-validation-unobtrusive-javascript.aspx

ASP.NET MVC - Ajax.BeginForm vs Ajax.ActionLink

I've noticed when I use Ajax.BeginForm (with a submit button) that the Model is passed to the Controller but when I use an Ajax.ActionLink it is not passed - or at least I have not discovered how to tap into it.
First question: How do you determine which is the better route to take?
Now, for a little deeper dive into one sample scenario: I have a model that has a couple dozen simple data type properties and a few List properties. The Create/Edit View is rendered with a Html.BeginForm(). The submit button returns the entire view model and I can then go through it and save all the data to the DB via the DB Model. Like I said I have a few List pieces as well. For example, I have a List of credit cards accepted which I render as a series of check boxes, a List of Services Provided also rendered as a list of check boxes. All of these are easy to deal with on the Form Post. However, I have one List that is basically a free-form text entry and I would like to have the textbox with an Add button followed by all of the List items, each with a delete button.
My Create/Edit view looks something like:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<RainWorx.FrameWorx.MVC.ViewModels.DirectoryEdit>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div class="Column12">
<div class="Shadow"></div>
<h2 class="h2row"><%= Model.PageTitle%></h2>
</div>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true)%>
<fieldset>
<%--<legend>Fields</legend>--%>
<div class="editor-label">
<%: Html.LabelFor(model => model.Name)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Name, new { style = "width:20em;" })%>
<%: Html.ValidationMessageFor(model => model.Name)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Address1)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Address1, new { style = "width:20em;" })%>
<%: Html.ValidationMessageFor(model => model.Address1)%>
</div>
...
<div class="editor-label">
<%: Html.LabelFor(model => model.LookupAccepts)%>
</div>
<div class="editor-field">
<hr />
<% foreach (var a in Model.MyAccepts)
{
if (a.Checked)
{ %>
<input type="checkbox" name="AcceptIDs" checked="checked" value="<%: a.ID %>" /> <%: a.Name%><br />
<% }
else
{ %>
<input type="checkbox" name="AcceptIDs" value="<%: a.ID %>" /> <%: a.Name%><br />
<% }
} %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.LookupServices)%>
</div>
<div class="editor-field">
<hr />
<% foreach (var a in Model.MyServices)
{
if (a.Checked)
{ %>
<input type="checkbox" name="ServiceIDs" checked="checked" value="<%: a.ID %>" /> <%: a.Name%><br />
<% }
else
{ %>
<input type="checkbox" name="ServiceIDs" value="<%: a.ID %>" /> <%: a.Name%><br />
<% }
} %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.MyLicenses)%>
</div>
<div class="editor-field">
<hr />
<% Html.RenderPartial("EditLicense", model: Model); %>
</div>
<div class="editor-label">
</div>
<div class="editor-field">
<input type="submit" value="Save" />
</div>
</fieldset>
<% } %>
</div>
<div>
<%: Html.ActionLink("Back to List", "Index")%>
</div>
</asp:Content>
The Partial View looks like:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%# Import namespace="RainWorx.FrameWorx.MVC" %>
<% foreach (var license in Model.MyLicenses) { %>
<% } %>
My thought train for setting it up this way is pretty straight forward (I think it is anyways). I only have something to Ajax on the License section. I want to add one string after another without losing all of the information for the main model. And after the add is done I want to update the partial view with the updated List for it.
There is probably a better way to do this than what I laid out and if so, lay it on me. The main part I am trying to figure out right now (and quickly) is whether Ajax.ActionLink (and my Extension methods for it) are the right direction to go.
An Ajax.BeginForm simply ajaxifies the given form and when you submit it the values of all input fields that it contains are sent to the server. The only difference with a normal form is that the they are sent using AJAX.
On the other hand Ajax.ActionLink generates a simple anchor tag which performs an AJAX request to the given url. It won't send any additional values to the server unless you specify it.
How do you determine which is the better route to take?
Personally I don't use any of those. I use standard Html.BeginForm and Html.ActionLink and write the code manually to AJAXify them unobtrusively with jQuery (if I need to use Ajax of course).
For your scenario of implementing dynamic list editing you may take a look at the following blog post.

asp.net MVC Handle Partial Postback Response

I have multiple pages containing the same partial view. The partial contains a form that posts to an action. After a post I want to return to the page I was on before the post. What's the best way to do this?
Example:
Partial View:
form post action = note/create/
Pages
page1:
products/index/
page2:
customer/details/
page3:
order/details/
These 3 pages contain the partial view, when posting the partial it redirects to note/create/. I need to return to the original page on success.
Thanks
Simon
Either have the post happen via AJAX -- thus not leaving the page, or pass the current controller/action/id (or the Url as a whole) as parameters to the action that handles the post. See below for an example of the later.
<% using (Html.BeginForm(...)) { %>
<input type='hidden'
name='currentController'
value='<%= ViewContext.RouteData["controller"] %>' />
<input type='hidden'
name='currentAction'
value='<%= ViewContext.RouteData["action"] %>' />
<input type='hidden'
name='<%= ViewContext.RouteData["id"] %>' />
...rest of form...
<% } %>
or
<% using (Html.BeginForm( ...,
new { ReturnUrl = Url.Action( ViewContext.RouteData["action"],
ViewContext.RouteData ) }, ... )) { %>
....
<% } %>
You can store the current page address in a hidden field and send it with Post request.
In your partial view:
<script type="text/javascript">
var field = document.getElementById("currentPage");
field.value=document.location.href;
</script>
<form method="post" action="note/create/">
...
<input type="hidden" value="" id="currentPage" name="currentPage" />
</form>
Then retrieve the address of the hidden input and redirect the user to it.

Resources