When I submit the form the values not inserting in razor engine mvc3? - asp.net-mvc-3

Below is my view page. without <form> tag when I insert the values, its perfectly inserting. But when I insert with <form> tag the values not inserting, the debug point pointing to [HttpGet] instead of [HttpPost]. For validation purpose I have inserted the <form> tag. But it seem to be no use.. Tell me the solution....
#model CustMaster.Models.MyAccount
#using CustMaster.Models
#{
ViewBag.Title = "Customer Information";
}
<html>
<head>
<title>Customer Information</title>
<link href="../../style.css" rel="stylesheet">
</head>
<body>
<form action="" id="contact-form" class="form-horizontal">
#using (Html.BeginForm())
{
<table>
<tr>
<td><h3>User Information</h3></td>
</tr>
</table>
<table>
<tr>
<td>
<div class="control-group">
#Html.LabelFor(model => model.CustomerFirstName,
new { #class = "control-label" })
<div class="controls">
#Html.TextBoxFor(model => model.CustomerFirstName,
new { #class = "input-xlarge" })
</div>
</div>
</td>
<td>
<div class="control-group">
#Html.LabelFor(model => model.CustomerMiddleName,
new { #class = "control-label" })
<div class="controls">
#Html.TextBoxFor(model => model.CustomerMiddleName,
new { #class = "input-xlarge" })
</div>
</div>
</td>
</tr>
</table>
<button type="submit">Register</button>
}
#*</form>*#
<script type="text/javascript" src="../../assets/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../../assets/js/jquery.validate.js"></script>
<script type="text/javascript" src="../../assets/js/jquery.validate.min.js"></script>
<script type="text/javascript" src="../../script.js"></script>
</body>
</html>
Below is my Controller
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(MyAccount myacc)
{
MyAccount ma = new MyAccount();
var objview = ma.GetCustInfo(myacc);
return View();
}

You cannot nest html forms => it results in invalid markup and undefined behavior. You will have to remove the outer <form>. The Html.BeginForm already generates a form tag. You seem to have commented the closing form tag but not the opening.
And please format your code a little. It's a complete mess to read:
#model CustMaster.Models.MyAccount
#using CustMaster.Models
#{
ViewBag.Title = "Customer Information";
}
<html>
<head>
<title>Customer Information</title>
<link href="#Url.Content("~/style.css")" rel="stylesheet">
</head>
<body>
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "contact-form" }))
{
<table>
<tr>
<td><h3>User Information</h3></td>
</tr>
</table>
<table>
<tr>
<td>
<div class="control-group">
#Html.LabelFor(model => model.CustomerFirstName, new { #class = "control-label" })
<div class="controls">
#Html.TextBoxFor(model => model.CustomerFirstName, new { #class = "input-xlarge" })
</div>
</div>
</td>
<td>
<div class="control-group">
#Html.LabelFor(model => model.CustomerMiddleName, new { #class = "control-label" })
<div class="controls">
#Html.TextBoxFor(model => model.CustomerMiddleName, new { #class = "input-xlarge" })
</div>
</div>
</td>
</tr>
</table>
<button type="submit">Register</button>
}
<script type="text/javascript" src="#Url.Content("~/assets/js/jquery-1.7.1.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/assets/js/jquery.validate.js")"></script>
<script type="text/javascript" src="#Url.Content("~/assets/js/jquery.validate.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/script.js")"></script>
</body>
</html>
Also please notice that I have fixed your script references by introducing url helpers instead of hardcoding the url to them.

Related

Ajax.BeginForm submitting the form twice

I have a problem with my modal on inserting data. Every time I add a new row it get's a second identical row into the database. I don't really know exactly what I did wrong so if you have a ideea on how to solve this please help me.
This is my controller:
public ActionResult IndexEvent()
{
return View(db.tbl_Event.ToList());
}
[HttpGet]
public ActionResult AddEvent()
{
return PartialView();
}
[HttpPost]
public ActionResult AddEvent(BOL3.tbl_Event eve)
{
if(ModelState.IsValid)
{
db.tbl_Event.Add(eve);
db.SaveChanges();
}
return PartialView("_Detail", db.tbl_Event.ToList());
}
,here is my Index view, _Detail partial view and Add partial view (in the same order):
#model IEnumerable<BOL3.tbl_Event>
#{
ViewBag.Title = "Index";
}
<link href="#Url.Content("~/Content/bootstrap/css/bootstrap.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/bootstrap/css/bootstrap-theme.min.cs")" rel="stylesheet" />
<link href="#Url.Content("~/Content/bootstrap/css/font-awesome.min.cs")" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<div id="main-div">
<div class="clearfix"> </div>
<div class="clearfix"> </div>
<div class="container">
<i class="glyphicon glyphicon-plus"></i> Add New
<br />
<br />
<div id="div-record">
#Html.Partial("_Detail")
</div>
</div>
</div>
<div class="modal fade" id="Add-Model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add Event</h4>
</div>
<div class="divForAdd">
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#Add').click(function (event) {
event.preventDefault();
$.get(this.href, function (response) {
$('.divForAdd').html(response);
});
$('#Add-Model').modal({
backdrop: 'static',
}, 'show');
});
#model IEnumerable<BOL3.tbl_Event>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Event Name</th>
<th>Starting Event (Date and Time)</th>
<th>Ending Event (Date and time)</th>
<th>All Day ?</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach(var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Event)
</td>
<td>
#Html.DisplayFor(modelItem => item.Start_Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.End_Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.All_Day)
</td>
<td>
<i class="glyphicon glyphicon-pencil"></i> Edit
</td>
<td>
#Ajax.ActionLink(" Delete", "DeleteEvent", "Prog", new { #id = item.ID }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div-record" }, new { #class = "glyphicon glyphicon-trash" })
</td>
</tr>
}
</tbody>
</table>
</div>
#model BOL3.tbl_Event
#using (Ajax.BeginForm("AddEvent", "Prog", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "div-record", OnSuccess = "$('.close').click()" }))
{
<div class="modal-body">
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pushpin"></i></span>
#Html.TextBoxFor(m => m.Event, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(m => m.Start_Date, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(m => m.End_Date, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(m => m.All_Day, new { #class = "form-control" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" name="cmd">Save</button>
</div>
}
I tried something else but that also gave me a problem (see this link: "Refresh table list using Ajax in Asp.Net Mvc") Thank you.
this problem is occuring because you have loaded <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> twice in the _layout page as well as index page and because of that it causes ajax to send request twice. so remove the link either from Index page or _layout page
Why it causes to submit twice?
if you look at the code of unobtrusive-ajax it has function $(document).on("click", "form[data-ajax=true] which is responsible for sending the request so when you submit the form this function trigger's differently on each script you loaded which causes the request to send twice (if someone can explain better feel free to edit)
It is because you have JS function binded to element #Add and you are not disabling anchror href correctly, thus having two requests (since your anchor has link attribute as well). In this SO question How can I disable HREF if onclick is executed? you can se, that correct click handling should be like
$('#Add').click(function (event) {
event.preventDefault();
$.get(this.href, function (response) {
$('.divForAdd').html(response);
});
$('#Add-Model').modal({
backdrop: 'static',
}, 'show');
return false; // this is essential
});

MVC3 razor view error Microsoft JScript runtime error: Object doesn't support property or method 'datepicker'`

I am trying to display a datepicker for my Html.EditorFor
To do this I created an EditorTemplate in my Views\Shared\EditorTemplate folder , Named it DateTime.cshtml
but it is not working ,instead I am getting error ---Microsoft JScript runtime error: Object doesn't support property or method 'datepicker'
Plz help me to fix this error
This is my razor view page
#model MyWebRole.ViewModels.ViewModelEvents
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset style="width:50%">
<legend>Event Details:</legend>
<div>
<table>
<tr>
<td>
#Html.EditorFor(model => model.vmStartDate)
#Html.ValidationMessageFor(model => model.vmStartDate)
</td>
</tr>
</table>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
and here is my DateTime.cshtml (pasted below)
#model System.DateTime?
<div class="editor-field">
#Html.TextBox("", String.Format("{0:MM/dd/yyyy}",(Model == DateTime.MinValue)? null : Model), new { #class="text"})
</div>
<script type="text/javascript">
$(document).ready(function () {
$("##ViewData.ModelMetadata.PropertyName").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'mm/dd/yy',
gotoCurrent: true
});
});
</script>
I am able to get datepicker working on another view
#model MyWebRole.Models.Events
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset style="width:50%">
<legend>Event Details:</legend>
<div>
<table>
<tr>
<td>
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</td>
</tr>
</table>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
The difference between the two razor views is that
-->the first one( (datepicker not working) is using a ViewModel as model ie(mywebrole.ViewModels.EventViewModel)
--> and the second one is using the myWebrole.models.Events (datepicker working fine)
Is this an issue ?
Given that error, I think the problem is the selector. Instead of $("##ViewData.ModelMetadata.PropertyName"), try this one:
$("input.text").datepicker({ ...
(Alternatively, you could #Html.TextBoxFor(model => model) instead of #Html.TextBox, so that way the input would get id=PropertyName, and thus the selector should work).
Also, you're sure the script for the datepicker JQuery plugin loaded successfully on the page, right?

MVC3 view rendering twice when I have Glimpse and use a MVC control toolkit DateTimeFor element

I have an MVC application with glimpse installed, I am also using the MVCControlToolkit for dymanic validation.
The issue I have is when I have a view that uses DateTimeFor to display the date time calendar with validation, but only in a very limited set of circumstances (if I only have datetimefor elements this doesn't happen), the body gets rendered on the page twice.
It looks like the rendering is getting restarted by something, but I haven't been able to work it out.
Any help would be appreciated
My view code is
#using LeaveTracker.Models
#using LeaveTracker.Models.Leave
#using MVCControlsToolkit.Controls
#using MVCControlsToolkit.Controls.Validation
#model LeaveTracker.Models.Leave.LeaveAllocation
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_LayoutMaintenance.cshtml";
}
#Html.AntiForgeryToken()
<div class="page-header">
<h1>
Edit Leave Allocation
#if (Model.ID > 0) { <small> #Model.TypeOfLeave.Name till #Model.AppliesUntil.ToString("dd/MM/yyyy")</small> }
</h1>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<link href="#Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/themes/base/jquery.ui.datepicker.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.16.min.js")" type="text/javascript"></script>
#Html.JQueryDatePickerGlobalizationScript("en-GB")
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/ValidationSetup.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MVCControlToolkit.Controls-1.5.0.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Leave Allocation Details</legend>
#Html.HiddenFor(model => model.ID)
<div class="clearfix">
#Html.LabelFor(model => model.TypeOfLeave)
<div class="input">
#Html.DropDownListFor(model => model.TypeOfLeave,
LeaveFactory.GetAllLeaveTypes().Select(fl => new SelectListItem
{
Text = fl.Name,
Value = fl.ID.ToString()
}))
<span class="help-inline">#Html.ValidationMessageFor(model => model.TypeOfLeave)</span>
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.AppliesFrom)
<div class="input">
#Html.DateTimeFor(model => model.AppliesFrom, DateTime.Today, true).DateCalendar(
inLine: false,
calendarOptions: new CalendarOptions
{
ChangeYear = true,
ChangeMonth = true
})
<span class="help-inline">#Html.ValidationMessageFor(model => model.AppliesFrom)</span>
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.AppliesUntil)
<div class="input">
#Html.DateTimeFor(model => model.AppliesUntil, DateTime.Today, true).DateCalendar(
inLine: false,
calendarOptions: new CalendarOptions
{
ChangeYear = true,
ChangeMonth = true
})
<span class="help-inline">#Html.ValidationMessageFor(model => model.AppliesUntil)</span>
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.DefaultAllocation)
<div class="input">
#Html.EditorFor(model => model.DefaultAllocation)
<span class="help-inline">#Html.ValidationMessageFor(model => model.DefaultAllocation)</span>
</div>
</div>
</fieldset>
<fieldset>
<legend>Leave Carried Over</legend>
<div class="clearfix">
#Html.LabelFor(model => model.MaxCarriesOver)
<div class="input">
#Html.EditorFor(model => model.MaxCarriesOver)
<span class="help-inline">#Html.ValidationMessageFor(model => model.MaxCarriesOver)</span>
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.LeaveUseByDate)
<div class="input">
#Html.DateTimeFor(model => model.LeaveUseByDate, DateTime.Parse("01/01/1900"), true).DateCalendar(
inLine: false,
calendarOptions: new CalendarOptions
{
ChangeYear = true,
ChangeMonth = true
})
<span class="help-inline">#Html.ValidationMessageFor(model => model.LeaveUseByDate)</span>
<span class="help-block">The year on this field doesn't matter, only the month and day will be taken into account</span>
</div>
</div>
<div class="actions">
#Html.ActionLink("Cancel", "Index", null, new { #class = "btn" })
<input class="btn primary" type="submit" value='Save'>
</div>
</fieldset>
}
Lee,
We believe we have fixed this issue.
Can you please test and confirm by installing the alpha build of Glimpse 0.87 from MyGet at http://www.myget.org/F/getglimpse/
If we get confirmation that this fixes your issue - and with a bit more testing - we will release to the main NuGet.org repository.
EDIT
Glimpse version 0.87 is now available from the main NuGet.org Glimpse feed

how can i get the value selected in #Html.DropDownList in a MVC3

I have this code, how can I get the selected value of the #htmlDropDownList to put this value in my #Url.Action instead of 1, I have read using javascript o jquery but i cant figure out how can i do that in the view directly, and this is not working for my
var idempresa = $('IdEmpresa').val()
<a href="#Url.Action("List","Script")?idempresa=**idempresa**"
the code:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Script</legend>
<div class="editor-label">
#Html.LabelFor(model => model.IdEmpresa, "Empresa")
</div>
<div class="editor-field">
#Html.DropDownList("IdEmpresa", String.Empty )
#Html.ValidationMessageFor(model => model.IdEmpresa)
</div>
</fieldset>
}
href="#Url.Action("List","Script")?idempresa=**1**"
pd. thank you for the help
Edit:
#using System.Web.Mvc.Html
#model SistemaDispositivos.Models.Script
#{
ViewBag.Title = "Script";
}
<h2>Script</h2>
<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Script</legend>
<div class="editor-label">
#Html.LabelFor(model => model.IdEmpresa, "Empresa")
</div>
<div class="editor-field">
#Html.DropDownList("IdEmpresa", String.Empty)
#Html.ValidationMessageFor(model => model.IdEmpresa)
</div>
</fieldset>
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var url1 = '#Url.Action("List","Script")?idempresa=';
$('IdEmpresa').change(function() {
$urlId = $('urlid');
$urlId.attr('href', url + $(this).val());
});
});
</script>
<a id="urlid" href="#Url.Action("List","Script")?idempresa=url1"> </a>
What iam missing?
well it work now this is what I wanted thank for the help:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Script</legend>
<div class="editor-label">
#Html.LabelFor(model => model.IdEmpresa, "Empresa")
</div>
<div class="editor-field">
#Html.DropDownList("IdEmpresa", string.Empty )
#Html.ValidationMessageFor(model => model.IdEmpresa)
</div>
</fieldset>
}
<script type="text/javascript" language="javascript">
function valid() {
var listaScriptUrl = '#Url.Action("List", "Script", new { idempresa = 0})';
var input = $('#IdEmpresa').val();
$('#Lista-Script').load(listaScriptUrl.replace('0', input));
}
</script>
<input type="button" value="Click Here" onclick="valid()">
<div id="Lista-Script">
</div>
so now in the div Lista-Script when I click the button I get my view that I wanted
The view would render HTML so you cannot get the selected value of dropdown list and put it back to the variable of the view which has already executed in the server side. What you could do is put an id on the tag and update the href on change event of dropdown.
$(document).ready(function(){
$('IdEmpresa').change(function(){
var val = $(this).val();
var newurl = $("urlid").attr("href") + val;
$("urlid").attr("href",newurl);
});
});
<a id="urlid" href="#Url.Action("List","Script")?idempresa="> </a>
I would approach this much like Bipins posted, with one major exception.
<fieldset>
<legend>Script</legend>
<div class="editor-label">
#Html.LabelFor(model => model.IdEmpresa, "Empresa")
</div>
<div class="editor-field">
#Html.DropDownList("IdEmpresa", *This needs to be a list of ListItems*, new { id = "idEmpresa" })
#Html.ValidationMessageFor(model => model.IdEmpresa)
</div>
</fieldset>
$(document).ready(function()
{
var url = '#Url.Action("List","Script")?idempresa=';
$('#idEmpresa').change(function()
{
$urlId = $('urlid');
$urlId.attr('href', $urlId.attr('href') + $('this').val());
}
});
By caching the original URL in a js variable, you always have a clean slate to append to.

MVC 3 Razor AJAX doesn't work

In EditPhoto.cshtml:
#model vg_music.Models.images
#{
ViewBag.Title = "EditPhoto";
}
<h2>
EditPhoto2</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Ajax.BeginForm(new AjaxOptions{UpdateTargetId = "AjaxDiv"})) {
#Html.ValidationSummary(true)
<div id="AjaxDiv">
#Html.Partial("EditPhotoForm")
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
EditPhotoForm.cshtml:
#model vg_music.Models.images
<fieldset>
<legend>images</legend>
#Html.HiddenFor(model => model.id)
<div class="editor-label">
#Html.LabelFor(model => model.title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.title)
#Html.ValidationMessageFor(model => model.title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.comment)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.comment)
#Html.ValidationMessageFor(model => model.comment)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.filename)
</div>
<div class="editor-field">
<img src="#Url.Content("~/uploads/images/little/"+Model.filename)" alt="#Model.title"/><br />
</div>
<p>
<input type="submit" value="Сохранить" />
</p>
</fieldset>
PhotosController.cs:
....
[HttpPost]
public ActionResult EditPhoto(images obj)
{
if (ModelState.IsValid)
{
var db = new EditImagesModel();
db.SaveImage(obj);
if (Request.IsAjaxRequest()) //This does not work.
{
return PartialView("EditPhotoForm");
}
return RedirectToAction("EditPhotos");
}
return View();
}
....
Why is not satisfied:
if (Request.IsAjaxRequest())
{
return PartialView("EditPhotoForm");
}
Why is not satisfied:
Because you forgot to include:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
in your EditPhoto.cshtml page. And because of this the Ajax.BeginForm helper doesn't perform any AJAX request but a simple form POST.
Contrary to ASP.NET MVC 1.0 and 2.0 where Ajax.* helpers such as Ajax.ActionLink and Ajax.BeginForm were polluting your markup with javascript obtrusively, in ASP.NET MVC 3 they simply generate HTML5 data-* attributes on the corresponding DOM elements. This way markup and javascript is kept separate. And you need javascript to interpret those attributes. This javascript is located in the jquery.unobtrusive-ajax.js script which needs to be included.

Resources