how can i get the value selected in #Html.DropDownList in a MVC3 - asp.net-mvc-3

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.

Related

MVC 5 Ajax posting whole form - instead of ajax call

I have a basic ajax call setup in MVC 5 but it seems that my Ajax form is actually posting the full form, instead of getting back PartialViewResult in the main view, the whole window just renders with the PartialView for the result
suggestion what I may be missing here ?
I also do have the following jquery renders in my _Layout.cshtml
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
MainView
#{
ViewBag.Title = "Puzzles 1 & 2";
}
<h2>#ViewBag.Title</h2>
<div>
#Html.Partial("Puzzle1Form")
</div>
PartialView
#model SixPivot_Code_Puzzles.Models.Puzzle1Model
#using (Ajax.BeginForm("Puzzle1","Puzzles",new AjaxOptions {
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "puzzle1-result",
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Puzzle1</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.IntegerList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.IntegerList, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.IntegerList, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Find Largest No." class="btn btn-default" />
</div>
</div>
</div>
}
<div id="puzzle1-result"></div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
}
Controller
[HttpPost]
public PartialViewResult Puzzle1(Puzzle1Model model)
{
if (ModelState.IsValid)
{
Puzzle1Model result = new Puzzle1Model();
result.LargestInteger = FindLargestInt(model.IntegerList).ToString();
result.IntegerList = model.IntegerList;
return PartialView("Puzzle1FormResult",result);
}
else {
return PartialView("Puzzle1Form",model);
}
}
PartialViewResult on Success (Puzzle1FormResult.cshtml)
#model SixPivot_Code_Puzzles.Models.Puzzle1Model
<div>
<h4>Largest Integer</h4>
<hr />
<p>
Largest Integer for the list "#Model.IntegerList" is : #Model.LargestInteger
</p>
</div>
I tend to try not use the Ajax helpers in MVC because I find jQuery easier to understand. You could try doing it how I would.
PartialView
#model SixPivot_Code_Puzzles.Models.Puzzle1Model
<form class="form-horizontal" id="frmPuzzle1">
#Html.AntiForgeryToken()
<div>
<h4>Puzzle1</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.IntegerList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.IntegerList, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.IntegerList, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Find Largest No." class="btn btn-default" />
</div>
</div>
</div>
<div id="puzzle1-result"></div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
*Notice I removed the scripts section, you should have this in your layout instead.
MainView
#{
ViewBag.Title = "Puzzles 1 & 2";
}
<h2>#ViewBag.Title</h2>
<div>
#Html.Partial("Puzzle1Form")
</div>
<script>
$(document).ready(function() {
$(document).on('submit', '#frmPuzzle1', function(e) {
// stop default form submission
e.preventDefault();
$.ajax({
url: '#Url.Action("Puzzle1", "Puzzles")',
type: 'POST',
data: $('#frmPuzzle1').serialize(),
success: function(html) {
$('#puzzle1-result').html(html);
}
});
});
});
</script>
The Ajax.* family of helpers simply add a standard HTML setup (a regular old form, for example) and some JavaScript that intercepts the default behavior, sending it as AJAX instead. In other words, the code is unobtrusive. If for whatever reason the JavaScript can't be run, it will fallback to standard behavior of doing a simple form post.
Therefore, if it's doing a standard form post, rather than sending an AJAX request, you most likely have some JavaScript error on the page that is preventing the AJAX code from running.
The Ajax.* family of helpers simply add a standard HTML setup (a regular old form, for example) and some JavaScript that intercepts the default behavior, sending it as AJAX instead. In other words, the code is unobtrusive. If for whatever reason the JavaScript can't be run, it will fallback to standard behavior of doing a simple form post.

When I submit the form the values not inserting in razor engine mvc3?

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.

HttpPost method is not fired if the submit button is disabled

I have a view as follows: DemoView.cshtml
#model Mvc3Razor.Models.UserModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Create</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 (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>UserModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.City)
#Html.ValidationMessageFor(model => model.City)
</div>
<p>
<input type="submit" value="Create" /></p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript">
$(function () {
$('input[type="submit"]').click(function () {
$(this).attr('disabled', 'disabled');
});
});
</script>
And a controller: HomeController.cs
[HttpPost]
public ViewResult Create(UserModel um)
{
if (!TryUpdateModel(um))
{
ViewBag.updateError = "Create Failure";
return View(um);
}
_usrs.Create(um);
return View("Details", um);
}
In order to prevent multiple button clicks, I am trying to disable the button once user clicks the Create button but once the Create button is disabled it is not firing the HttpPost method.
Can anyone help me out in order to resolve this issue?
Try disabling the button when the form is submitted and not when the submit button is clicked:
$("form").submit(function() {
$(this).attr("disabled", "disabled");
return true;
});
What I will suggest is to redirect user back to Index Page upon Successfull Post. You want use PRG Pattern
Post, Redirect, Get (PRG) pattern in which it is "to help avoid
duplicate form submissions and allow web applications to behave more
intuitively with browser bookmarks and the reload button"
usrs.Create(um);
//Redirect to Index Page here
see this SO question for more details

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

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