DateTime field is null when passing to controller in ASP.NET MVC5 - c#

I have in my application a search form using AjaxBeginForm. In the same I have a date field (DateTime), and in which I am using the datePicker bootstrap.
My form looks like this:
#using (Ajax.BeginForm("Index", "Pedido", new AjaxOptions { HttpMethod = "Get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "divPedidos" }, new { #class = "form-inline" }))
{
#Html.TextBox("pesquisarRascunhoId", 0, new { style = "display: none" })
<div class="row">
<div class="col-sm-4">
<p>Data emissão</p>
<div class="input-group date col-sm-5">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
#Html.EditorFor(model => model.PedidoFilter.EmissaoInicial, new { htmlAttributes = new { #class = "form-control input-sm datepicker" } })
</div>
a
<div class="input-group date col-sm-5">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
#Html.EditorFor(model => model.PedidoFilter.EmissaoFinal, new { htmlAttributes = new { #class = "form-control input-sm datepicker" } })
</div>
</div>
<div class="btn-search">
<p class="demo-button">
<button type="submit" class="btn btn-success"><i class="fa fa-search"></i><span>Pesquisar</span></button>
</p>
</div>
}
My javaScript for formatting my date in dd / mm / yyyy looks like this:
$(".datepicker").datepicker({
format: "dd/mm/yyyy",
language: "pt-BR",
autoclose: true
});
My entity looks like this:
public class PedidoFilter
{
public DateTime? EmissaoInicial { get; set; }
public DateTime? EmissaoFinal { get; set; }
}
And finally my controller looks like this:
public ActionResult Index(PedidoResult pedidoResult,
{
var pedido = _service.FindAll(pedidoResult.PedidoFilter);
return View(pedido);
}
I define my language culture in my Web.config like this:
<globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" />
All fields of my form arrive in my controller, but my date fields are always null, in the format dd/mm/yyyy, which I define in my datepicker js.
If I enter a date in the mm/dd/yyyy format it is passed to my controller.
My question is:
How can I pass my date field in the dd/mm/yyyy format and get them on my controller without them being null?

I think the date format can be changed with Culture or via the code example below: C# takes the first month of the year after the day. You solve this problem. Use the flatpickr or other datepicker.
<input asp-for="Birthdate" type="datetime" data-name="date-picker" class="form-control" autocomplete="off">
let birthDay = flatpickr(document.getElementById('Birthdate'), {
enableTime: true,
dateFormat: 'd-m-Y',
});
$('#myform').submit((e) => {
$('#Birthdate').val(birthDay.latestSelectedDateObj.toLocaleString());
});

Related

Modal/Partial view uk date conflict MVC5

I am having a problem with jquery validation within a Modal/Partial View as it's conflicting with my main view. The main issue is with #Scripts.Render("~/bundles/jqueryval") as when I add it to my main view, the main form will no longer submit (doesn't hit the controller) as the validation is rejecting UK style dates (as you can see in my code, I am using DateITA to solve this problem in my Modal and submits with no issues)
I have tried moving #Scripts.Render("~/bundles/jqueryval") to the partial view & the main page will now submit, but it breaks my submit for the Modal. I have also tried naming the main view form & modal form to apply the validation to just the modal, but this hasn't helped.
Thanks
Main view
#model Puspers2.ViewModels.ContractViewModel
#{
ViewBag.Title = "Contract";
}
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "mainForm" }))
{
<div class="form-group form-inline datepickerWidth">
<div class='input-group date mydatepicker datepickerWidth'>
#Html.TextBoxFor(m => m.TblContract.OrderPlacedDate, new { title = "Order Placed Date", placeholder = "dd/mm/yyyy", #class = "form-control datepickerWidth", onclick = "this.select()", id = "orderPlacedDate" })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class='form-group form-inline datepickerWidth'>
<div class='input-group date mydatepicker datepickerWidth'>
#Html.TextBoxFor(m => m.TblContract.ContractStartDate, new { title = "Contract Start Date", placeholder = "dd/mm/yyyy", #class = "form-control datepickerWidth", id = "contractStartDate", onclick = "this.select()" })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<!--SAVE BUTTON-->
<br /><br /><br /><br />
<div class="form-group absolute">
<hr />
<button type="submit" class="btn btn-primary btn-lg saveButtonPadding" value="save" formaction="ContractUpdate" formmethod="post" id="saveButton">Save</button>
</div>
<!--SAVE BUTTON-->
}
<!--div to hold the Partial view that forms the modal-->
<div class="form-group">
#Html.Partial("_ContractContributionDetails")
</div>
<!--end div to hold the Partial view that forms the modal-->
#section scripts{
#Scripts.Render("~/bundles/jqueryval")
<script>
//Modal
$(document).on('click', '#SaveContractContribution', function () {
var $form = $('#modalForm')
.validate({
rules: {
TblContractContributionHistory_CommencementDeductions: {
dateITA: true
}
}
});
if ($form.valid()) {
$.ajax({
async: false,
type: 'POST',
url: 'ContractContributionHistoryAdd',
datatype: "json",
data: {
contractNumber: $("#contractNumber").val(),
commencementDeductions: $('#TblContractContributionHistory_CommencementDeductions').val(),
deductionsCategoryId: $('#deductionsCategory').val(),
numberOfContributions: $('#TblContractContributionHistory_NumberOfContributions').val(),
employeeContributionReference: $('#TblContractContributionHistory_EmployeeContributionReference').val(),
teamMember: $('#TblContractContributionHistory_TeamMemberId').val()
},
success: function (data) {
location.reload();
}
});
}
});
// >> JS snippet to handle datepicker functionality >>
$(function () {
$('.mydatepicker').datetimepicker({
locale: 'en-gb',
format: 'DD/MM/YYYY',
showTodayButton: true,
showClear: true,
})
.on('dp.hide', function () { // on hiding data picker, record associated entryfield to allow focus to be set when built-in blur happens
dateField = $(this).find('input');
$("#contractStartDate,#contractEndDate,#actualTerminationDate").trigger("change")
PickerClosing = true;
});
// on exit from date field, check if caused by picker closing. If Yes, set focus back in field
$('.mydatepicker input').blur(function (e) {
if (PickerClosing == true) {
PickerClosing = false;
dateField.focus();
}
});
});
// << JS snippet to handle datepicker functionality <<
</script>
}
Partial View
#model Puspers2.ViewModels.ContractViewModel
#Scripts.Render("~/Scripts/jquery-1.10.2.js")
#Scripts.Render("~/Scripts/jquery-3.3.1.js")
#Scripts.Render("~/scripts/jquery-ui-1.12.1.min.js")
#Scripts.Render("~/scripts/bootbox.js")
#Scripts.Render("~/Scripts/bootstrap.js")
#Scripts.Render("~/Scripts/respond.js")
#Scripts.Render("~/Scripts/moment.js")
#Scripts.Render("~/Scripts/moment-with-locales.js")
#Scripts.Render("~/Scripts/bootstrap-datetimepicker.js")
#{
}
#using (Ajax.BeginForm("ContractContributionHistoryAdd", "Home", new AjaxOptions
{ }, new { id = "modalForm" }))
{
<div>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content modalContentDeductions">
<h2 class="modal-header">Add Deduction</h2>
<div class="modal-body">
<p class="dateLabels"><strong>Deductions Commenced On</strong></p>
<div class='form-group form-inline modalDatepickerWidth'>
<div class='input-group date mydatepicker modalDatepickerWidth'>
#Html.TextBoxFor(m => m.TblContractContributionHistory.CommencementDeductions, new { title = "Commencement Deductions", #class = "form-control inputSizeMedium" })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class='form-group'>
#Html.LabelFor(m => m.TblContractContributionHistory.DeductionsCategoryId, new { title = "Payment" })
#Html.DropDownListFor(m => m.TblContractContributionHistory.DeductionsCategoryId, new SelectList(Model.TblDeductionsCategoryLOOKUP, "DeductionsCategoryId", "Category"), "Select Option", new { #class = "form-control inputSizeMedium", #id="deductionsCategory"})
#Html.ValidationMessageFor(m => m.TblContractContributionHistory.DeductionsCategoryId)
</div>
<div class="form-group">
#Html.LabelFor(m => m.TblContractContributionHistory.EmployeeContributionReference, new { title = "Monthly Cost To Employee" })
#Html.TextBoxFor(m => m.TblContractContributionHistory.EmployeeContributionReference, new { title = "Monthly Cost To Employee", #class = "form-control inputSizeMedium" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.TblContractContributionHistory.NumberOfContributions, new { title = "" })
#Html.TextBoxFor(m => m.TblContractContributionHistory.NumberOfContributions, new { title = "", #class = "form-control inputSizeMedium" })
</div>
<div class='form-group'>
#Html.LabelFor(m => m.TblContractContributionHistory.TeamMemberId, new { title = "" })
#Html.DropDownListFor(m => m.TblContractContributionHistory.TeamMemberId, new SelectList(Model.TblTeamMembersLOOKUP, "TeamMemberId", "TeamMemberName"), "Select Option", new { #class = "form-control inputSizeMedium" })
#Html.ValidationMessageFor(m => m.TblContractContributionHistory.TeamMemberId)
</div>
<br />
<div>
<button id="SaveContractContribution" class="btn btn-primary btn-lg" value="save" formmethod="post">Save</button>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
}
#section scripts
{
<script>
$(function () {
$.validator.unobtrusive.parse('#modalForm');
});
$(function () {
$('.mydatepicker').datetimepicker({
locale: 'en-gb',
format: 'DD/MM/YYYY',
showTodayButton: true,
showClear: true,
})
.on('dp.hide', function () { // on hiding data picker, record associated entryfield to allow focus to be set when built-in blur happens
dateField = $(this).find('input');
$("#contractStartDate,#contractEndDate,#actualTerminationDate").trigger("change")
PickerClosing = true;
});
// on exit from date field, check if caused by picker closing. If Yes, set focus back in field
$('.mydatepicker input').blur(function (e) {
if (PickerClosing == true) {
PickerClosing = false;
dateField.focus();
}
});
})
</script>
}
DateITA
$.validator.addMethod( "dateITA", function( value, element ) {
var check = false,
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/,
adata, gg, mm, aaaa, xdata;
if ( re.test( value ) ) {
adata = value.split( "/" );
gg = parseInt( adata[ 0 ], 10 );
mm = parseInt( adata[ 1 ], 10 );
aaaa = parseInt( adata[ 2 ], 10 );
xdata = new Date( Date.UTC( aaaa, mm - 1, gg, 12, 0, 0, 0 ) );
if ( ( xdata.getUTCFullYear() === aaaa ) && ( xdata.getUTCMonth() === mm - 1 ) && ( xdata.getUTCDate() === gg ) ) {
check = true;
} else {
check = false;
}
} else {
check = false;
}
return this.optional( element ) || check;
}, $.validator.messages.date );

DateTime value is not sending back to controller

I cant seem to find the problem here. Really stuck and need help. Im using Html.BeginForm and inside i have editorFor - model.DOB. Used post method but somehow it doesnt send the property back to my controller. Do help. I have other string property fields which is sending fine to the controller. Only date property not sending. TQVM in advance.
---------Edit---------
Just found out that if i use Edge - i need to use dd/MM/yyyy format. Then it will saves fine. If i use MM/dd/yyyy, then it will give null on the controller.
On chrome
using dd/MM/yyyy - gives me 'The field must be a date' error
using MM/dd/yyyy - gives me null.
---------Edit---------
Model
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date of Birth")]
public DateTime? PersonDOB { get; set; }
View
#model Models.CorporationModel
using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<div class="form-group">
#Html.LabelFor(model => model.PersonDOB, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PersonDOB, new { htmlAttributes = new { #class = "form-control", placeholder = "Format: 06/31/1998" } })
#Html.ValidationMessageFor(model => model.PersonDOB, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" name="action:PersonalSave" />
<input type="submit" value="Reprocess" class="btn btn-default" onclick="return confirm('Are you sure?')" name="action:PersonalReprocess" />
</div>
</div>
</div>
}
Controller
[HttpPost]
[MultipleButton(Name = "action", Argument = "PersonalReprocess")]
public ActionResult PersonalReprocess(int id, CorporationModel corporationModel, HttpPostedFileBase postedResultFile, HttpPostedFileBase postedPersonalFile)
{
corporationModel.Verified = "Processing";
return UpdatePersonal(id, corporationModel, postedResultFile, postedPersonalFile);
}
If i remove the
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
Im getting the 'The field must be a date error'. If i switch between month and date manually, then it saves without problem. However, when it pulls from the db, it will start with dd/mm/yyyy and then clicking on save will gives out 'the field must be a date error' again, so need to switch it manually.

MVC Pass value from view to dynamic partial view

I'm trying to make a partial view, which will add dynamically as much fields as I input. I input number of fields, then I want to choose days of week in formed fields and do some work with this data in controller, but I have a problem with passing amount of days in partial view.
Controller :
public class CoursesController : Controller
{
private SchoolContext db = new SchoolContext();
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "CourseId,Name,Language,LanguageProficiency,StartDate,EndDate,TeacherId,NumberOfLessonsPerWeek")] Course course)
{
if (ModelState.IsValid)
{
db.Courses.Add(course);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(course);
}
public ActionResult ShowDaysOfweek(int? countDays)
{
//countDays = 2;
ViewBag.CountDays = countDays;
var days = new List<DayOfWeek> { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday };
ViewBag.DaysOfWeek = new SelectList(days);
return PartialView("ShowDaysOfweek");
}
}
In this View I can add patial view by clicking button in script:
#model SchoolManagementSystem.Models.Course
#using (Ajax.BeginForm(new AjaxOptions { }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" }
<div class="form-group">
#Html.Label("Number Of Lessons Per Week", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-5">
#Html.TextBox("NumberOfLessonsPerWeek", null, htmlAttributes: new { #class = "form-control", #type = "number", #id = "numberOfLessonsPerWeek" })
</div>
<div>
<input type="button" value="Add days" id="Show" class="btn btn-default" />
</div>
</div>
<div id="ShowResults">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<script type="text/javascript">
var url = '#Url.Action("ShowDaysOfweek", "Courses")';
$('#Show').on("click", function () {
var countDays = $('#numberOfLessonsPerWeek').val();
url += '/?countDays=' + countDays;
$('#ShowResults').load(url);
})
</script>
Partial view:
#for (var i = 0; i < ViewBag.CountDays; i++)
{
<div class="form-group">
#Html.Label("Day of week", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-5">
#Html.DropDownList("DaysOfWeek", (IEnumerable<SelectListItem>)ViewBag.DaysOfWeek, htmlAttributes: new { #class = "form-control", style = "height: 35px" })
</div>
</div>
}
Is it possible to do something? Thanks!
First create the hidden field with partial view url
<input type="hidden" value="#Url.Action("ShowDaysOfweek", "Courses", new { countDays= "numberOfLessonsPerWeek" })" id="hdnURLShowDaysOfweek" />
in javascript read the url and replace the parameter
<script type="text/javascript">
var url = $('#hdnURLShowDaysOfweek').val();
$('#Show').on("click", function () {
url = url.replace("numberOfLessonsPerWeek",$('#numberOfLessonsPerWeek').val());
$('#ShowResults').load(url);
})
</script>

Binding bootstrap datetimepicker to knockoutmodel

Im using a bootstrap datetimepicker to input appointment datetimes to a knockout viewmodel. the viewmodel has an object appointment which holds the observable values for all appointment object. Im sending the appointment to the controller via an ajax call, however after many null values for my dates i found that you must create a custom binding for the datepicker. after implementing the custom binding on the git page of the datepicker i am still receiving null values for both the start and end dates.
Have i implemented the custom binding incorrectly?
Code:
View:
<div class="form-horizontal">
<h4>Appointment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Start, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="container">
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<div class='input-group date' id='startdatepicker'>
<input type='text' class="form-control" data-bind="date: appointment.start, format: 'DD MMM YYYY'" /><span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
#Html.ValidationMessageFor(model => model.Start, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.End, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="container">
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<div class='input-group date' id='enddatepicker'>
<input type='text' class="form-control" data-bind="date: appointment.end, format: 'DD MMM YYYY'" /><span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
#Html.ValidationMessageFor(model => model.End, "", new { #class = "text-danger" })
</div>
</div>
Scripts section at bottom of view
#section Scripts {
#Scripts.Render("~/bundles/jqueryval",
"/Scripts/ViewModels/AppointmentFormViewModel.js")
<script>
$(function () {
$('#startdatepicker').datetimepicker();
$('#enddatepicker').datetimepicker();
});
var viewModel = new AppointmentFormViewModel(#Html.HtmlConvertToJson(Model));
ko.applyBindings(viewModel);
</script>
}
Knockout viewmodel
function AppointmentFormViewModel(appointment) {
var self = this;
self.saveCompleted = ko.observable(false);
self.sending = ko.observable(false);
self.isCreating = appointment.id == 0;
self.appointment = {
id: appointment.id,
start: ko.observable(appointment.start),
end: ko.observable(appointment.end),
text: ko.observable(appointment.text),
clientid: ko.observable(appointment.clientid),
employeeid: ko.observable(appointment.employeeid),
roomid: ko.observable(appointment.roomid),
};
ko.bindingHandlers.date = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
ko.utils.registerEventHandler(element, 'change', function () {
var value = valueAccessor();
if (element.value !== null && element.value !== undefined && element.value.length > 0) {
value(element.value);
}
else {
value('');
}
});
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
var allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
var pattern = allBindings.format || 'DD/MM/YYYY';
var output = "-";
if (valueUnwrapped !== null && valueUnwrapped !== undefined && valueUnwrapped.length > 0) {
output = moment(valueUnwrapped).format(pattern);
}
if ($(element).is("input") === true) {
$(element).val(output);
} else {
$(element).text(output);
}
}
};
here is the appointment model object that was sent from the knockout viewmodel
as you can see the date time is not what was selected
Here is how it posted to server
is creating is a variable to determine whether the form is editing or creating an appointment
self.appointment.__RequestVerificationToken = form[0].value;
$.ajax({
url: (self.isCreating) ? 'Create' : 'Edit',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: ko.toJS(self.appointment)
})

ASP .NET MVC Form fields Validation (without model)

I am looking for a way to validate two fields on ASP View page. I am aware that usual way of validating form fields is to have some #model ViewModel object included on a page, where the properties of this model object would be annotated with proper annotations needed for validation. For example, annotations can be like this:
[Required(ErrorMessage = "Please add the message")]
[Display(Name = "Message")]
But, in my case, there is no model included on a page, and controller action that is being called from the form receives plane strings as method arguments.
This is form code:
#using (Html.BeginForm("InsertRssFeed", "Rss", FormMethod.Post, new { #id = "insertForm", #name = "insertForm" }))
{
<!-- inside this div goes entire form for adding rssFeed, or for editing it -->
...
<div class="form-group">
<label class="col-sm-2 control-label"> Name:</label>
<div class="col-sm-10">
<div class="controls">
#Html.Editor("Name", new { htmlAttributes = new { #class = "form-control", #id = "add_rssFeed_name" } })
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> URL:</label>
<div class="col-sm-10">
<div class="controls">
#Html.Editor("Url", new { htmlAttributes = new { #class = "form-control", #id = "add_rssFeed_Url" } })
</div>
</div>
</div>
</div>
</div>
<!-- ok and cancel buttons. they use two css classes. button-styleCancel is grey button and button-styleOK is normal orange button -->
<div class="modal-footer">
<button type="button" class="button-styleCancel" data-dismiss="modal">Close</button>
<button type="submit" class="button-styleOK" id="submitRssFeed">Save RSS Feed</button>
</div>
}
You can see that form is sending two text fields (Name and Url) to the RssController action method, that accepts these two string parameters:
[HttpPost]
public ActionResult InsertRssFeed(string Name, string Url)
{
if (!String.IsNullOrEmpty(Name.Trim()) & !String.IsNullOrEmpty(Url.Trim()))
{
var rssFeed = new RssFeed();
rssFeed.Name = Name;
rssFeed.Url = Url;
using (AuthenticationManager authenticationManager = new AuthenticationManager(User))
{
string userSid = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.PrimarySid);
string userUPN = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.Upn);
rssFeedService.CreateRssFeed(rssFeed);
}
}
return RedirectToAction("ReadAllRssFeeds", "Rss");
}
If the page would have model, validation would be done with #Html.ValidationSummary method, but as I said I am not using modelview object on a page.
Is there a way to achieve this kind of validation without using ModelView object, and how to do that? Thanks.
If you are looking for server side validation you can use something like below using
ModelState.AddModelError("", "Name and Url are required fields.");
but you need to add
#Html.ValidationSummary(false)
to your razor view inside the Html.BeginForm section, then code will looks like below.
[HttpPost]
public ActionResult InsertRssFeed(string Name, string Url)
{
if (String.IsNullOrEmpty(Name.Trim()) || String.IsNullOrEmpty(Url.Trim()))
{
ModelState.AddModelError("", "Name and URL are required fields.");
return View();
}
var rssFeed = new RssFeed();
rssFeed.Name = Name;
rssFeed.Url = Url;
using (AuthenticationManager authenticationManager = new AuthenticationManager(User))
{
string userSid = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.PrimarySid);
string userUPN = authenticationManager.GetUserClaim(SystemClaims.ClaimTypes.Upn);
rssFeedService.CreateRssFeed(rssFeed);
}
return RedirectToAction("ReadAllRssFeeds", "Rss");
}
If you are looking for only client side validation, then you have to use client side validation library like Jquery.
http://runnable.com/UZJ24Io3XEw2AABU/how-to-validate-forms-in-jquery-for-validation
Edited section for comment
your razor should be like this.
#using (Html.BeginForm("InsertRssFeed", "Rss", FormMethod.Post, new { #id = "insertForm", #name = "insertForm" }))
{
#Html.ValidationSummary(false)
<div class="form-group">
<label class="col-sm-2 control-label"> Name:</label>
<div class="col-sm-10">
<div class="controls">
#Html.Editor("Name", new { htmlAttributes = new { #class = "form-control", #id = "add_rssFeed_name" } })
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> URL:</label>
<div class="col-sm-10">
<div class="controls">
#Html.Editor("Url", new { htmlAttributes = new { #class = "form-control", #id = "add_rssFeed_Url" } })
</div>
</div>
</div>
</div>
</div>
<!-- ok and cancel buttons. they use two css classes. button-styleCancel is grey button and button-styleOK is normal orange button -->
<div class="modal-footer">
<button type="button" class="button-styleCancel" data-dismiss="modal">Close</button>
<button type="submit" class="button-styleOK" id="submitRssFeed">Save RSS Feed</button>
</div>
}
Hope this helps.

Categories

Resources