In a MVC view, i have 2 forms with as many fields like bellow
LoginRegisterModel.cs
public class LoginRegisterViewModel {
public string LoginUsername { get; set; }
public string LoginPassword { get; set; }
public string RegisterUsername { get; set; }
public string RegisterPassword { get; set; }
public string RegisterFirstName { get; set; }
public string RegisterLastName { get; set; }
}
LoginRegistte.cshtml (1st form)
#model LoginRegisterViewModel
#using (Html.BeginForm("Login", "MemeberController", FormMethod.Post, new {})) {
#Html.LabelFor(m => m.LoginUsername)
#Html.TextBoxFor(m => m.LoginUsername)
#Html.LabelFor(m => m.LoginPassword)
#Html.TextBoxFor(m => m.LoginPassword)
<input type='Submit' value='Login' />
}
2nd form
#using (Html.BeginForm("Register", "MemeberController", FormMethod.Post, new {})) {
#Html.LabelFor(m => m.RegisterFirstName)
#Html.TextBoxFor(m => m.RegisterFirstName)
#Html.LabelFor(m => m.RegisterLastName)
#Html.TextBoxFor(m => m.RegisterLastName)
#Html.LabelFor(m => m.RegisterUsername)
#Html.TextBoxFor(m => m.RegisterUsername)
#Html.LabelFor(m => m.RegisterPassword)
#Html.TextBoxFor(m => m.RegisterPassword)
<input type='Submit' value='Register' />
}
MemberController.cs
[HttpGet]
public ActionResult LoginRegister() {
LoginRegisterViewModel model = new LoginRegisterViewModel();
return view("LoginRegister", model);
}
[HttpPost]
public ActionResult Login(LoginRegisterViewModel model) {
if (ModelState.IsValid)
{
//some logic
}
else
{
return view(model);
}
}
[HttpPost]
public ActionResult Register(LoginRegisterViewModel model) {
if (ModelState.IsValid)
{
//some logic
}
else
{
return view(model);
}
}
in this when i am directly click on 1st form button that time i want fire validations for 1st form.but i am getting two forms validations at a time. what i do in controller or some where else?
Try like this,
Form1
#model LoginRegisterViewModel
#using (Html.BeginForm("Login", "MemeberController", FormMethod.Post, new {id="frmLogin"})) {
#Html.LabelFor(m => m.LoginUsername)
#Html.TextBoxFor(m => m.LoginUsername)
#Html.LabelFor(m => m.LoginPassword)
#Html.TextBoxFor(m => m.LoginPassword)
<input type='Submit' value='Login' id="btnLogin" />
}
Form2
#using (Html.BeginForm("Register", "MemeberController", FormMethod.Post, new {id="frmRegister"})) {
#Html.LabelFor(m => m.RegisterFirstName)
#Html.TextBoxFor(m => m.RegisterFirstName)
#Html.LabelFor(m => m.RegisterLastName)
#Html.TextBoxFor(m => m.RegisterLastName)
#Html.LabelFor(m => m.RegisterUsername)
#Html.TextBoxFor(m => m.RegisterUsername)
#Html.LabelFor(m => m.RegisterPassword)
#Html.TextBoxFor(m => m.RegisterPassword)
<input type='Submit' value='Register' id= "btnRegister" />
}
Script
$(document).ready(function () {
$('#btnLogin').click(function () {
var validation = $("#frmLogin");
if (!validation.valid()) {
return false;
}
});
$('#btnRegister').click(function () {
var validationRegi = $("#frmRegister");
if (!validationRegi.valid()) {
return false;
}
});
});
It looks like just a typo here:
#using (Html.BeginForm("Login", "MemeberController", FormMethod.Post, new {}))
MemeberController should be MemberController.
It is in 2 spots, so make sure you catch both of them.
Related
I am facing an issue with saving message to my database. I am using Twilio account and the message is sent. However, I cant save it to the database. In my views, I type in a message then I send it through the sender. However when checking the _context.Messages.Add(message); I get a message:
"The function requires all threads to run"
so I click the little icon next to it and then it displays null instead of the message above.
public class ApplicationDbContext : DbContext
{
public DbSet<Message> Messages { get; set; }
public ApplicationDbContext()
: base()
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public class MessageController : Controller
{
private ApplicationDbContext _context;
private IMessageSender _messageSender;
public MessageController(IMessageSender messageSender)
{
this._messageSender = messageSender;
_context = new ApplicationDbContext();
}
[ActionName("MessageStatus")]
public ActionResult Send(Message message)
{
var viewModel = new MessageViewModel
{
Message = new Message()
};
_context.Messages.Add(message);
_messageSender.Send(message);
return View("MessageStatus", viewModel);
}
}
my view
#model MessagingWebApplication.ViewModel.MessageViewModel
#{ ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Sms</h2>
#using (Html.BeginForm("MessageStatus", "Message"))
{
#Html.ValidationSummary()
<div class="form-group">
#Html.LabelFor(m => m.Message.Reciever)
#Html.TextBoxFor(m => m.Message.Reciever, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Reciever)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Message.Sender)
#Html.TextBoxFor(m => m.Message.Sender, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Sender)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Message.Body)
#Html.TextBoxFor(m => m.Message.Body, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Body)
</div>
#Html.HiddenFor(m => m.Message.Id)
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary">Send</button>
You need to save after adding message
_context.Messages.Add(message);
_context.SaveChanges();
or asynchronously
await _context.Messages.AddAsync(message);
await _context.SaveChangesAsync();
i am new to asp.net and i have a question. I have created a simple form fro sending sms, however my id always stays null. Can you please advise on what am i doing wrong? I used exactly the same form in my other page and it worked fine.
#model MessagingWebApplication.ViewModel.MessageViewModel
#{ ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Sms</h2>
#using (Html.BeginForm("MessageStatus", "Message"))
{
#Html.ValidationSummary()
<div class="form-group">
#Html.LabelFor(m => m.Message.Reciever)
#Html.TextBoxFor(m => m.Message.Reciever, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Reciever)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Message.Sender)
#Html.TextBoxFor(m => m.Message.Sender, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Sender)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Message.Body)
#Html.TextBoxFor(m => m.Message.Body, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Body)
</div>
#Html.HiddenFor(m => m.Message.Id)
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary">Send</button>
}
My model
public class Message
{
[Key]
public int Id { get; set; }
[Required]
public string Sender { get; set; }
[Required]
public string Reciever { get; set; }
[Required]
public string Body { get; set; }
}
Method used for sending
public ActionResult Send(Message message)
{
var viewModel = new MessageViewModel
{
Message = new Message()
};
_context.Add(message);
_context.SaveChanges();
_messageSender.Send(message);
return View("MessageStatus", viewModel);
}
here _context.SaveChanges(); i get SqlException: Cannot insert the value NULL into column 'Id', table 'MyDatabase.dbo.Messages'; column does not allow nulls. INSERT fails.
My issue was that i had failed when updating the database so i just followed this How to delete and recreate from scratch an existing EF Code First database
I am using kendoui grid with ClientTemplate to show textbox on each row of the grid.
I need to show validation messages on each empty textbox of the grid on click of a button outside the grid which will actually post the data.
View
#(Html.Kendo().Grid<MMM.Lumos.Entities.CustomEntities.OrganizationRiskViewModel>()
.Name("OrgRiskGrid")
.DataSource(dataSource => dataSource.Ajax()
.Model(model =>
{
model.Id(m => m.RiskId);
model.Id(m => m.RiskTierId);
model.Id(m => m.RiskTierKey);
model.Id(m => m.RiskKey);
})
.Read(read => read.Action("GetRiskType", "RiskTier").Data("getRiskTier"))
.Events(events =>
events.Error("error"))
)
.Columns(columns =>
{
columns.Bound(c => c.RiskName).Width(50);
columns.Bound(c => c.ATPTestMix).ClientTemplate(Html.Kendo().IntegerTextBox().Name("ATPTestMix").Min(0).HtmlAttributes(new { value = "", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
columns.Bound(c => c.VITestMix).ClientTemplate(Html.Kendo().IntegerTextBox().Name("VITestMix").Min(0).HtmlAttributes(new { value = "", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
columns.Bound(c => c.SMTestMix).ClientTemplate(Html.Kendo().IntegerTextBox().Name("SMTestMix").Min(0).HtmlAttributes(new { value = "", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
})
)
Model
public class OrganizationRiskViewModel
{
public int OrganizationId { get; set; }
public short RiskTierId { get; set; }
public string RiskTierName { get; set; }
public short RiskId { get; set; }
public string RiskName { get; set; }
[Required(ErrorMessage="ATP Test Mix is mandatory")]
public short ATPTestMix { get; set; }
[Required(ErrorMessage = "ATP Test Mix is mandatory")]
public short SMTestMix { get; set; }
[Required(ErrorMessage = "ATP Test Mix is mandatory")]
public short VITestMix { get; set; }
public string RiskTierKey { get; set; }
public string RiskKey { get; set; }
}
I tried setting the data annotations on the model to which the Grid is binded but unfortunately it didnt work.
Let me know if any one has the solution for the same.
<script type="text/javascript">
$(function () {
var form = $('#yourFormName');
form.data('validator').settings.ignore = ''; // default is ":hidden".
});
</script>
//Set DataAnnotation attributes
public IList<SelectListItem> SecretQuestion1IdList { get; set; }
[DisplayName("Answer to First Secret Question")]
[Required]
public string SecretQuestionAnswer1 { get; set; }
[DisplayName("Second Secret Question")]
[Required]
public int SecretQuestion2Id { get; set; }
public IList<SelectListItem> SecretQuestion2IdList { get; set; }
[DisplayName("Answer to Second Secret Question")]
[Required]
public string SecretQuestionAnswer2 { get; set; }
[Required]
public int TrustedDomainId { get; set; }
public IList<SelectListItem> TrustedDomain { get; set; }
}
#model ExternalUserManagement.Web.Mvc.Controllers.ViewModels.Register.RegisterPageViewModel
#{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="accountDetails" class="centre-container">
#using (Ajax.BeginForm("CreateAccount", "Register",
new AjaxOptions
{
UpdateTargetId = "accountDetails",
OnBegin = "windowHelper.displayWaitingDialog('Saving Registration Details, please wait...')",
OnComplete = "windowHelper.close()"
}))
{
<p class="message information">Register you details, then click submit.</p>
<div class="row">
#Html.LabelFor(m => m.FirstName, new { #class = "label" })
#Html.TextBoxFor(m => m.FirstName, new { #class = "input k-textbox" })
</div>
<div class="row">
#Html.LabelFor(m => m.LastName, new { #class = "label" })
#Html.TextBoxFor(m => m.LastName, new { #class = "input k-textbox" })
</div>
<div class="row">
#Html.LabelFor(m => m.CompanyEmail, new { #class = "label" })
#Html.TextBoxFor(m => m.CompanyEmail, new { #class = "input-left k-textbox" })
#
#(Html.Kendo().DropDownListFor(m => m.TrustedDomainId)
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Model.TrustedDomain)
.OptionLabel(" -- Please Select --")
.HtmlAttributes(new { #class = "input-right" })
)
</div>
<div class="row">
#Html.LabelFor(m => m.BirthDate, new { #class = "label" })
#Html.Kendo().DatePickerFor(m => m.BirthDate).HtmlAttributes(new { #class = "input" })
</div>
<div class="row">
#Html.LabelFor(m => m.SecretQuestion1Id, new { #class = "label" })
#(Html.Kendo().DropDownListFor(m => m.SecretQuestion1Id)
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Model.SecretQuestion1IdList)
.OptionLabel(" -- Please Select --")
.HtmlAttributes(new { #class = "input" })
)
</div>
<div class="row">
#Html.LabelFor(m => m.SecretQuestionAnswer1, new { #class = "label" })
#Html.TextBoxFor(m => m.SecretQuestionAnswer1, new { #class = "input k-textbox" })
</div>
<div class="row">
#Html.LabelFor(m => m.SecretQuestion2Id, new { #class = "label" })
#(Html.Kendo().DropDownListFor(m => m.SecretQuestion2Id)
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Model.SecretQuestion2IdList)
.OptionLabel(" -- Please Select --")
.HtmlAttributes(new { #class = "input" }).AutoBind(true)
)
</div>
<div class="row">
#Html.LabelFor(m => m.SecretQuestionAnswer2, new { #class = "label" })
#Html.TextBoxFor(m => m.SecretQuestionAnswer2, new { #class = "input k-textbox" })
</div>
<div class="captcha row">
#Html.Label("Are you a human?", new { #class = "label" })
<br />
#Html.Raw(Html.GenerateCaptcha("captcha", "clean"))
#Html.ValidationMessage("Invalid Characters")
</div>
<div class="row">
<div class="commands">
<button class="k-button" type="submit" title="Sumbit">
<img src="#Url.Content("~/Content/Images/Icons/disk.png")" alt="" />
Sumbit
</button>
</div>
</div>
}
</div>
Please have a look the following
Link:
http://macaalay.com/2014/02/15/enabling-asp-net-mvc-client-validation-for-kendo-ui-components/
So this is the code, i have 2 submit buttons when i press "Start" I want it to send the Datetime.now to the start row, and when i press "Stop" i want it to send the Stop datetime.now to the column, this should be happening in the same row. And when i press Start again it should generate a new ID 2, etc. print the start date on the second row.
Exampel ID 1 : Start 2013-11-15 05:12 Slut : 2013-11-15 05:15
Greetings Patrik
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.Start)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Start, new { style = "display: none;", #Value = #DateTime.Now })
#Html.ValidationMessageFor(model => model.Start)
</div>
<p>
<input type="submit" name="#Html.NameFor(x => x.Command)" value="Start" formaction="/tider/create" />
</p>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.Slut)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Slut, new { #Value = #DateTime.Now })
#Html.ValidationMessageFor(model => model.Slut)
</div>
<p>
<input type="submit" name="#Html.NameFor(x => x.Command)" value="Stop" />
</p>
}
</fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Slut)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Slut, new { #Value = #DateTime.Now })
#Html.ValidationMessageFor(model => model.Slut)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
controller
{
public class TiderController : Controller
{
private TiderDBContext db = new TiderDBContext();
//
// GET: /Tider/
public ActionResult Index()
{
return View(db.Tider.ToList());
}
//
// GET: /Tider/Details/5
public ActionResult Details(int id = 0)
{
ArbetsTider arbetstider = db.Tider.Find(id);
if (arbetstider == null)
{
return HttpNotFound();
}
return View(arbetstider);
}
//
// GET: /Tider/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Tider/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ArbetsTider arbetstider)
{
if (ModelState.IsValid)
{
db.Tider.Add(arbetstider);
db.SaveChanges();
}
return View(arbetstider);
}
//
// GET: /Tider/Edit/5
public ActionResult Edit(int id = 0)
{
ArbetsTider arbetstider = db.Tider.Find(id);
if (arbetstider == null)
{
return HttpNotFound();
}
return View(arbetstider);
}
//
// POST: /Tider/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ArbetsTider arbetstider)
{
if (ModelState.IsValid)
{
db.Entry(arbetstider).State = EntityState.Modified;
return RedirectToAction("Index");
}
return View(arbetstider);
}
//
// GET: /Tider/Delete/5
public ActionResult Delete(int id = 0)
{
ArbetsTider arbetstider = db.Tider.Find(id);
if (arbetstider == null)
{
return HttpNotFound();
}
return View(arbetstider);
}
//
// POST: /Tider/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
ArbetsTider arbetstider = db.Tider.Find(id);
db.Tider.Remove(arbetstider);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[HttpPost]
public ActionResult Start(ArbetsTider model)
{
using (var context = new TiderDBContext())
{
context.Tider.FirstOrDefault(x => x.ID == model.ID).Start = model.Start;
context.SaveChanges();
}
return View("Index");
}
[HttpPost]
public ActionResult Stop(ArbetsTider model)
{
using (var context = new TiderDBContext())
{
context.Tider.FirstOrDefault(x => x.ID == model.ID).Slut = model.Slut;
context.SaveChanges();
}
return View("Index");
}
}
}
model
public class ArbetsTider
{
public int ID { get; set; }
public DateTime Start { get; set; }
public DateTime Slut { get; set; }
}
public class TiderDBContext : DbContext
{
public DbSet<ArbetsTider> Tider { get; set; }
}
You need to use Ajax method to submit the one form partially without refreshing the whole page.
Try something like this:
First change like this(remove type='submit'):
#using (Html.BeginForm("Create", "Tider", FormMethod.Post, new { #id= "formStart" } ))
{
// html code
<input id="submittStartDate" name="#Html.NameFor(x => x.Command)" value="Start" class="submitButton" />
});
And
#using (Html.BeginForm("Stop", "Tider", FormMethod.Post, new { #id= "formStop" } ))
{
//html
<input id="stop" name="#Html.NameFor(x => x.Command)" value="Stop" class="submitButton" />
//html
});
Then add a function in javascript file:
$(document).ready(function () {
$("input.submitButton").click(function() {
SubmitForm(this);
});
});
function SubmitForm(input) {
var url = "";
var formData = "";
if(input[0].id == "formStart")
{
url = "../Tider/Create";
data = $('form#formStart').serialize();
}
else if(input[0].id == "formStop") {
url = "../Tider/Stop";
data = $('form#formStop').serialize();
}
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
// Do your stuff here
},
error: function () {
alert("Error in saving");
}
});
}
You need to change the return types of the C# methods Create and Stop to required type(I think you need int here) and retun that. And you will get the data "success" function of the Ajax call.
How to send id of a model property Name to Controller class in an MVC4 application
public class{
public Name{get;set;}
}
For Accesing name using id of that property
Update:
Here if change Name using jquery at runtime i want to send the changed name id to the controller class
UPDate:
This is my VIew
<script type="text/javascript">
$(function () {
$('.editor input').blur(function () {
$(this).hide();
$(this).closest('p').find('label').html($(this).val()).show();
});
$('.editor label').click(function () {
$(this).hide();
$(this).closest('p').find('input').show();
});
});
#using (Html.BeginForm("Homepage", "Home", FormMethod.Post))
{
<div class="editor">
<p>
#Html.LabelFor(x => x.Name, Model.Name)
#Html.EditorFor(x => x.Name)
<input type="submit" value="OK" />
</p>
<p>
#Html.LabelFor(x => x.Company, Model.Company)
#Html.EditorFor(x => x.Company)
<input type="submit" value="OK" />
</p>
<p>
#Html.LabelFor(x => x.City, Model.City)
#Html.EditorFor(x => x.City)
<input type="submit" value="OK" />
</p>
</div>
<input type="submit" value="OK" />
}
This is my model
public class Details
{
public string Name
{ get; set; }
public string Company
{ get; set; }
public string City
{ get; set; }
}
This is my COntroller methods
public ActionResult Homepage(Details d)
{
d.Name = "Rakesh";
d.Company = "TCS";
d.City = "DElhi";
return View(d);
}
[HttpPost, ActionName("Homepage")]
public ActionResult Indexof(Details d)
{
return View(d);
}
Here i am editing and sending data to the controller but my problem is when i click on Rakesh for example and change the name then i need to click button twice then only the changed data is sent to the controller class
Model:
public class SomeModel {
public string Name { get; set; }
}
Controller:
[HttpPost]
public ActionResult YourAction( SomeModel m )
{
if( ModelState.IsValid )
{
// use model
var name = m.Name;
return RedirectToAction( "Index", "Home" );
}
return View( m );
}
If this isn't what you need, please clarify what's this "id" you're talking about.