Setting the text-box value as the subject in Mailto functionality. - c#

I have created a custom html helper in MVC for MailTo functionality.
But I got an requirement to set the subject of the mail to the value user have entered in another textbox field.
I am not sure how to achieve this, Can some body please help?
Thanks
Html Helper
public static MvcHtmlString SendMailTo(this HtmlHelper helper, string emailAddress, string subject, string displayText)
{
var sb = string.Format("{3}",
CharEncode("mailto:"), CharEncode(emailAddress),CharEncode("?subject=" +subject), CharEncode(displayText));
return new MvcHtmlString(sb);
}
public static string CharEncode(string value)
{
var enc = System.Text.Encoding.Default;
var retval = "";
for (var i = 0; i < value.Length; i++)
{
retval += "&#" + enc.GetBytes(new[] { Convert.ToChar(value.Substring(i, 1)) })[0] + ";";
}
return retval;
}
View:
<div class="form-group">
#Html.LabelFor(m => m.ApplicationId, new { #class = "col-sm-3 control-label" })
<div class="col-sm-8">
#Html.TextBoxFor(m => m.ApplicationId, new {#class = "form-control"})
</div>
</div>
<div class="form-group">
<div class="col-sm-11" style="text-align:right">
#Html.SendMailTo("info#test.com", "Password Request: ", "Request Password")
<button type="submit" class="button">Sign in</button>
</div>
</div>

You can not get that value without any jquery code.
You should make an event on keyup ( for example ) on your texbox ( this is the one which is used as an user mail input )
Put your email form in a partial view and update that partial when that event is triggered.
INFO :
A) To render your ParialView use can Html.Partial helper -> Example here
B) To get textbox value you can use following jquery code
`$('.class of your textbox').val()' //will return a string
C) To update your partial view
c.1 Place your partial view in a `div element`
c.2 Make an `ajax` call from `jquery` to an action which returns your partial view filled with data
Example for c.2:
*AJAX*
$.ajax({
type:"GET",
data:{
mail:$('.class of your textbox').val()
},
success: function(response){
$(".class of your div").html(response.Html);
}
error: function(response){
// whatever you want to do
}
});
*Controller Action*
public JsonResult(string mail)
{
var model = new CustomModel(){ Mail=mail }; // custom class to your as model for your partial view
var html = RenderPartial(...) // method you can find in the link posted below
return Json(
{
Html=html
},JsonRequestBehavior.AllowGet)
}
Link I was writing about few lines above - follow this link
You can call that ajax on whatever event you want for your textbox.

Related

getting anchor tag href on click from Action Method

I have a grid which includes below hyperlink row,currently for all rows we have same hyperlink and only ID is changing and it is working fine.
<a href=" + #ViewBag.Url+ ID + " target='_blank'>Test</a>
Now for every row, we have different link url which i would get from action method when I pass ID.
I want to call MVC Action Method to get hyperlink url and then open it in another tab.How can I accomplish this?
I tried this one but it is not opening hyperlink?
<div class="row">
<div class="col-md-4">
Click Here;
</div>
</div>
public string GetPDFUrl(string id)
{
return "test.com" + id;
}
There are several ways to solve your problem. one of them is using child actions.
Put your generating URL part into a partial view to put your logic in your action method. So, create a child action method that can only be called in your views.
[ChildActionOnly]
public ActionResult GenerateUrlPartial(int id)
{
var generatedUrl = "";//your url business is here
var model = new UrlInfo { Url = generatedUrl };
return PartialView(model);
}
Then, create GenerateUrlPartial.cshtml partial view :
#model UrlInfo
#{
Layout = null;
ViewBag.Title = "GenerateUrlPartial";
}
<div class="row">
<div class="col-md-4">
Click Here;
</div>
</div>
And in your loop, call the action method like this :
#for (int i = 0; i < 10; i++)
{
Html.RenderAction("GenerateUrlPartial", new { id = i });
}
Hope this helps.

how make a script refresh and redirecting for Ajax.BeginForm MVC

I created a form using Ajax.BeginForm
#using (Ajax.BeginForm("CreatePlayer", "Admin", null, new AjaxOptions() { HttpMethod = "post" }))
{
<div class="row">
<div class="col-md-6">
<div class="text-style-roboto form-group">
<label>Имя</label>
#Html.TextBoxFor(x => x.Name, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Name)
</div>
<div class="form-group">
<button type="submit" class="button button-create">Добавить</button>
</div>
</div>
</div>
}
When I push the button to make a new player, a player is created but the form stays filled.
,
The desired behaviour is that the form should be cleared, but it doesn't. I don't how to clear the form using jQuery. Should I refresh the page, or some other way.
My post action in controller is -
[HttpPost]
public JsonResult CreatePlayer(CreatePlayerModel model, string TeamNameId)
{
if (ModelState.IsValid)
{
if (TeamNameId != string.Empty)
{
try
{
int newTeamId = int.Parse(TeamNameId);
repository.CreatePlayer(model, newTeamId);
TempData["message"] = string.Format("Игрок {0} {1} сохранены", model.Name, model.Surname);
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = "success" }
};
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
}
}
IEnumerable<SelectListItem> list = new SelectList(repository.Teams, "Id ", "Name");
ViewBag.ChoosingTeam = list;
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = "error" }
};
}
If it's needed, I can do the action by html forms to Ajax.
If you are using AJAX, the form would not be cleared automatically and you need to clear it. You can set values of input text and textareas to ''. Also, you need to reset the values of selects.
Assuming that the form id is CreatePlayer then to set the values of input text and textarea to blank ('') -
$('#CreatePlayer').find("input[type=text], textarea").val('');
Similarly, you can set the value of select to default value of your choice. Assuming that the select to be reset by the first option and the id of select is teamSel, then to reset the value -
$("#teamSel").val($("#teamSel option:first").val());
If you have a reset button added in the form, you can trigger the reset but that won't set the default values to form inputs. To trigger the reset -
$("#CreatePlayer").trigger('reset');
__ UPDATE ___
You should be calling these(depending on your requirement), in OnSuccess and/or OnFailure.
You should clear the form when AJAX call returns with success. That said, inside OnSuccess, clear the form.
You should show errors if OnFailure is called.

Custom validation in MVC not executing on partial views

So I have file uploading input which is strongly typed and below is the model class
public class UploadImageAlbum
{
[CustomFileValidator]
public HttpPostedFileBase Images { get; set; }
}
and my CustomFileValidator class is as below:
[AttributeUsage(AttributeTargets.Property,AllowMultiple =true,Inherited =false)]
public class CustomFileValidator : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext context)
{
const int maxContent = 1024 * 1024 * 50;//50 MB
var sAllowedExt = new string[] { ".jpg", ".png" };
var file = value as HttpPostedFileBase;
//Check for null
if (file == null)
{
return new ValidationResult("Please select an image to upload");
}
//Check for File Extension
if (sAllowedExt.ToList().Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
return new ValidationResult("Please Upload a valid file of type : " + string.Join(",", sAllowedExt));
}
//Check for length of file
if(file.ContentLength>maxContent)
{
return new ValidationResult("File is too large, maximum allowed size is :" + (maxContent / 1024) + "MB");
}
return ValidationResult.Success;
}
}
and my partialview is as below:
#using (Html.BeginForm("UploadImages", "Admin", FormMethod.Post, htmlAttributes: new { id = "frmUploadImages", novalidate = "novalidate", autocomplete = "off", enctype = "multipart/form-data" }))
{
<div class="form-group">
<span class="btn btn-default btn-file-img">
Browse #Html.TextBoxFor(m => m.UIAModel.Images, new { type = "file", multiple = "multiple", data_charset = "file" })
</span>
<span class="text-muted" id="filePlaceHolder">No files selected</span>
#Html.ValidationMessageFor(m=>m.UIAModel.Images, null, htmlAttributes: new { #class = "invalid" })
</div>
<div class="form-group">
<button class="btn btn-primary addImage pull-right">
<i class="fa fa-upload"></i> Upload
</button>
</div>
}
and below is how I load partialview on click of a link:
$('#page-inner').empty().load('/Admin/GetMediaUploadView', function () {
$.validator.unobtrusive.parse($('form#frmUploadImages'));
//Apply client validation for partialviews
})
But even after following all the steps, it isn't displaying any message and point to note is, if I add [Required] attribute for the same, it will work well, but custom validation what I have never displays any message. What else I have to add to make this CustomValidator to work? I followed this post but still could not be of much help. Also if anyone let me know how to update this model so as to accept multiple images, it will be of great help.
In order to get client side validation, your attribute must
implement IClientValidatable which will add the associated
data-val-* attributes to you html, and
you must include scripts to add methods to the jQuery validator.
This article is a good guide to creating custom client and server side validation attributes.
Note also your current attribute is rather limited in that the file types and size are fixed, and it would be more flexible to include properties to specify the file types and maximum file size so that you could use it as (say)
[FileValidation(MaxSize="1024", FileType="jpg|png")]
public HttpPostedFileBase Images { get; set; }
This article provide an example of an attribute that validates the file type, but could be adapted to include the MaxSize property.
Side note: If your loading dynamic content, then you should first set the validator to null
var form = $('form#frmUploadImages');
form.data('validator', null);
$.validator.unobtrusive.parse(form);

How to validate a field is not empty

I have a view as abcd.cshtml with below code
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.id)
#Html.HiddenFor(model => model.createtime)
<h3>Headline</h3>
<div class="editor-field">
#Html.EditorFor(model => model.general)
#Html.ValidationMessageFor(model => model.general)
</div>
<a class="anchor" id="keywords"></a>
<h3>Keywords</h3>
<div class="editor-field">
#Html.EditorFor(model => model.keywords)
#Html.ValidationMessageFor(model => model.keywords)
</div>
<a class="anchor" id="relatedcq"></a>
<h3>Related CQ</h3>
<div class="editor-field">
#Html.EditorFor(model => model.relatedcq)
#Html.ValidationMessageFor(model => model.relatedcq)
</div>
<p>
<input type="submit" value="Create" class="btn btn-primary" />
</p>
}
</div>
The controller is simple abcd.cs, I just put this into a DB
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(staging staging)
{
staging.modifiedby = User.Identity.Name;
staging.lastmodified = DateTime.Now;
staging.createtime = DateTime.Now;
try
{
db.stagings.Add(staging);
db.SaveChanges();
}
catch (InvalidOperationException e)
{
ViewData["error"] = "An error has occured: " + e.Message;
return View(staging);
}
return RedirectToAction("Details/" + staging.id);
}
What I want is to make sure that Keywords is filled. If Keywords is filled I need to have a pop up window saying "Please fill the Keywords".
I tried doing that using MessageBox.Show() but then for that I had to add System.Windows.Forms and that had some conflicts with System.Web.Mvc;
If you're using htmlhelper ValidationMessageFor would'nt you rather display a Validation Summary to the user the shows him/her all the fields that you require filled in?
e.g.
If you have a model and you have multiple fields that need to be filed in, which can be validated by decorating those fields/properties with the [Required] attribute, or any other that you see fit e.g. [StringLength] etc.
If you do that you can provide a validation summary, using the model binder to not post youre data if it doesnt meet the set validation.
Validation summary example:
#Html.ValidationSummary(false, "Please provide the details above and then click submit.")
That above will display all the validation errors of all fields marked with the following e.g. #Html.ValidationMessageFor(model => model.relatedcq)
Image of how the output, if there are validation errors, will be displayed.
Hope this helps :)
To achieve this you need to create a custom validation attribute on server side. So for e.g. Let's name it as MustBeFilled. Your new attribute would look like:
public class MustBeFilledAttribute : ValidationAttribute, IClientValidatable // IClientValidatable for client side Validation
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
return new ValidationResult(FormatErrorMessage(null));
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ValidationType = "mustbefilled",
ErrorMessage = ErrorMessage //Added
};
modelClientValidationRule.ValidationParameters.Add("param", metadata.DisplayName); //Added
return new List<ModelClientValidationRule> { modelClientValidationRule };
}
}
Now you would need a client side script as well to take action if the rule fails. As in your case you want to show a popup. Add below to your site script and make sure it renders after the Jquery-validation-* scripts are rendered.
(function ($) {
$.validator.addMethod('mustbefilled', function (value, element, params) {
if ($(element).val() != '')
return true;
alert('Fill it first.');
// Here you need to Invoke the modal popup.
return false;
}, '');
$.validator.unobtrusive.adapters.add('mustbefilled', ['param'], function (options) {
options.rules["mustbefilled"] = '#' + options.params.requiredif;
options.messages['mustbefilled'] = options.message;
});
})(jQuery);
To apply this custom validation, first add the attribute on your Model property.
[MustBeFilled]
public string Keywords { get; set; }
Then add the custom javascript to bundle.config, only if you have kept the code in separate file named mustbefilled.js. Here I intentionally added the javascript file with validation plugin so you don't get exception if it rendered before the validation plugin.
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*",
"~/Scripts/mustbefilled.js"));
That's it you're all set.
Now all you have to do is create a model pop and call it in the mustbefilled.js where I placed the comment to invoke it. See this sample here which would help you create a bound modal popup to your keywords property.

Return a value from a model to the controller

I have an application where if the joint owner == yes it should show a partialview. My Model.cs is
[Display(Name = "Joint Owner")]
public string JointOwner { get; set; }
and my view is
<div class="form-group">
#Html.LabelFor(m => m.JointOwner, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
<label>#Html.RadioButtonFor(m => m.JointOwner, new { #class = "form-control", value="Yes"}) Yes</label>
<label>#Html.RadioButtonFor(m => m.JointOwner, new { #class = "form-control", value = "No" }) No</label>
#Html.ValidationMessageFor(m => m.JointOwner)
</div>
</div>
I need it to return a partialview when the value of yes is selected. How would I handle this in the model? or would it be more advised to use javascript/jquery?
public ActionResult PrimaryApplicant(PrimaryApplicantViewModel model)
{
// Make sure session didn't get eaten.
var loanType = "";
if (Session["LoanType"] != null)
{
loanType = Session["LoanType"].ToString();
}
// Here we decide which view to show next. in the frotn end you may need to handle what to change labels to in the wizard maybe via JQ/JS
if (loanType == "Auto Refinance")
{
return PartialView("AutoRefinance");
}
else if (loanType == "Auto Purchase")
{
return PartialView("AutoPurchase");
}
else
{
// You'd want to actually handle it if somehow you got a bad value, I just did it so VS didn't whine.
return PartialView("PrimaryApplicantPartial");
}
}
It would b better if you use jQuery if you want an instant result rather than handling it on the back-end/models. If your not fond of the partial view, just make it a hidden div and if Joint Owner Says yes, just make it visible. You can use jQuery hide and show.
It is more preferable to use jquery, and you can use like that:
first create the container for partial view in your view i.e.
<div class="table-rec-container"></div>
then create a function inside the document.ready() like this:
function Partialview() {
var chkradio = $('#JointOwner').val();
if(chkradio ==true)
{
jQuery.ajax({
url: 'url of partial view',
type: "GET",
success: function (data) {
$('.table-rec-container').html("");
$('.table-rec-container').html(data);
}
});
}
}

Categories

Resources