Why the value is changed after clicking the submit button? - asp.net-mvc

I make one action method for 2 activities (new input and edit), and there is also only one
view to handle those activities.
But I don't understand no matter what activity happen, the action method always think it is a new input.
I learned that it because of the ID is always 0, but the problem is, when doing the edit, when in the view the ID is correct as the ID of the data, but when I click the submit button, the action method just see the 0 value of ID.
Here is the action method I used:
[HttpPost]
public ActionResult AddAssignment(SateliteSchedule SatSched)
{
var txt = "";
if (ModelState.IsValid)
{
if (SatSched.ID == 0)
{
db.SateliteSchedules.Add(SatSched);
txt = "{0} has been added!";
}
else
{
db.Entry(SatSched).State = EntityState.Modified;
txt = "{0} has been modified!";
}
db.SaveChanges();
Utility utl = new Utility();
TempData["message"] = string.Format(txt, utl.GetSateliteName(SatSched.SateliteID));
return RedirectToAction("FormAssignment");
}
else
{
ViewBag.Message = "ModelState is not Valid!";
return View("ErrorView");
}
}
And here is the view:
#using (Html.BeginForm("AddAssignment", "admin", FormMethod.Post))
{
#Html.ValidationSummary(true)
<table>
<tr>
<td>#Html.LabelFor(m => m.Tanggal)
</td>
<td>
#Html.EditorFor(m => m.Tanggal)
#Html.ValidationMessageFor(m => m.Tanggal)
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.SateliteID)</td>
<td>
#Html.DropDownList("SateliteID", (IEnumerable<SelectListItem>)ViewBag.SatList, "--- Satelite ---")
#Html.ValidationMessageFor(m => m.SateliteID)
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.WMOnDuty)</td>
<td>
#Html.DropDownList("WMOnDuty", (IEnumerable<SelectListItem>)ViewBag.WMList, "--- Worship Manager ---")
#Html.ValidationMessageFor(m => m.WMOnDuty)
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.SMOnDuty)</td>
<td>#Html.EditorFor(m => m.SMOnDuty)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.WLOnDuty)</td>
<td>#Html.EditorFor(m => m.WLOnDuty)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.MLOnDuty)</td>
<td>#Html.EditorFor(m => m.MLOnDuty)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.SoundMan)</td>
<td>#Html.EditorFor(m => m.SoundMan)</td>
</tr>
<tr>
<td valign=top>#Html.LabelFor(m => m.Note)</td>
<td>#Html.TextAreaFor(model => model.Note, new { #class = "memo-text" })</td>
</tr>
</table>
<div>
<input type="submit" value="Save" />
#Html.ActionLink("Kembali", "FormAssignment")
</div>
}
What should I check to fix this?

You have to have the Id as a hidden, so when you go in the method the model will have the id asigned to it (does it make sense?). try placing this in your form
#Html.HiddenFor(m => m.ID)

Related

How to calculate total value from razor view with javascript? MVC project

I got a .Net project using MVC and Razor.
I pass to the view a list containing products, where I have ProdutoValor( product value) with a TextboxFor for QuantidaVenda (Number os itens sold) for each iten. I want to get the value "QuantidadeVenda * ProdutoValor" for each item and show in a textbox the total value. How can I manage to do that with javascript?
I wanto to calculate the total as soon as the user enters the quantity
here is my view :
#for (int i = 0; i < Model.Produtos.Count; i++)
{
<tr>
<td>
#Html.HiddenFor(model => model.Produtos[i].ProdutoId)
#Html.HiddenFor(model => model.Produtos[i].ProdutoDescricao)
#Html.DisplayFor(model => model.Produtos[i].ProdutoNome)#Html.HiddenFor(model => model.Produtos[i].ProdutoNome)
</td>
<td>
#Html.DisplayFor(p => p.Produtos[i].ProdutoValor, new { #class = "form-control", Value = Model.Produtos[i].ProdutoValor }) #Html.HiddenFor(model => model.Produtos[i].ProdutoValor)
</td>
<td>
#Html.DisplayFor(p => p.Produtos[i].ProdutoEstoque, new { #class = "form-control", Value = Model.Produtos[i].ProdutoEstoque })#Html.HiddenFor(model => model.Produtos[i].ProdutoEstoque)
</td>
<td>
#if (Model.Produtos[i].ProdutoEstoque < 1)
{
#Html.TextBoxFor(p => p.Produtos[i].QuantidadeVenda, new { value = 0, disabled = "disabled" })
}
else
{
#Html.TextBoxFor(p => p.Produtos[i].QuantidadeVenda, new { value = 0, #id = "quantidade" })
if (Model.Produtos[i].ProdutoEstoque < Model.Produtos[i].QuantidadeVenda)
{<p>valor invalido</p>}
}
</td>
</tr>
}
[enter image description here][1]
how the list looks like
For Javascript:
Onchange Event for QuantidadeVenda(quantity):
function onchange()
{
var total= document.getElementById("name of total textbox").Value*
document.getElementById("name of quantity textbox").value
document.getElementById("name of total textbox").innerHTML=total
}
Jquery:
on change or LostFocus Event
$("input").change(function(){
var total= $("#name of total textbox").val()*
$("#name of quantity textbox").val()
$("#name of total textbox").val=total
});
Updated Code
HTML:
<table border="1">
<tr>
<td>product</td>
<td>quantity</td>
<td>total</td>
</tr>
<tr>
<td>
10
</td>
<td>
<input type="text" name="txt" value="" onchange="myFunction(this)">
</td>
<td><label>_</label></td>
</tr>
<tr>
<td>
10
</td>
<td>
<input type="text" name="txt" value="" onchange="myFunction(this)">
</td>
<td><label>_</label></td>
</tr>
</table>
Javascript:
function myFunction($this) {
debugger $($this).parent().siblings(":last").find('label').text($($this).parent().siblings().first().text().trim() * $this.value)
}

Linq selecting some fields in MVC

I am trying to select some fields and send them to MVC View but it gives me this error
The model item passed into the dictionary is of type System.Collections.Generic.List'1[<>f__AnonymousType6'2[System.String,System.String]], but this dictionary requires a model item of type System.Collections.Generic.IEnumerable'1[IdentitySample.Models.ApplicationUser].
Here is my code:
public ActionResult Index()
{
var con = new ApplicationDbContext();
var allusers = (from u in con.Users
where u.Message != null
select new { UserName = u.UserName, Message = u.Message });
return View(allusers.ToList());
}
and in the View:
#model IEnumerable<IdentitySample.Models.ApplicationUser>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>#Html.DisplayNameFor(model => model.Message)</th>
<th>#Html.DisplayNameFor(model => model.Email)</th>
<th>#Html.DisplayNameFor(model => model.EmailConfirmed)
</th>
<th>#Html.DisplayNameFor(model => model.PasswordHash)
</th>
<th>#Html.DisplayNameFor(model => model.SecurityStamp)
</th>
<th>#Html.DisplayNameFor(model => model.PhoneNumber)
</th>
<th>#Html.DisplayNameFor(model => model.PhoneNumberConfirmed)
</th>
<th>#Html.DisplayNameFor(model => model.TwoFactorEnabled)
</th>
<th>#Html.DisplayNameFor(model => model.LockoutEndDateUtc)
</th>
<th>#Html.DisplayNameFor(model => model.LockoutEnabled)
</th>
<th>#Html.DisplayNameFor(model => model.AccessFailedCount)
</th>
<th>#Html.DisplayNameFor(model => model.UserName)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.Message)
</td>
<td>#Html.DisplayFor(modelItem => item.Email)
</td>
<td>#Html.DisplayFor(modelItem => item.EmailConfirmed)
</td>
<td>#Html.DisplayFor(modelItem => item.PasswordHash)
</td>
<td>#Html.DisplayFor(modelItem => item.SecurityStamp)
</td>
<td>#Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
<td>#Html.DisplayFor(modelItem => item.PhoneNumberConfirmed)
</td>
<td>#Html.DisplayFor(modelItem => item.TwoFactorEnabled)
</td>
<td>#Html.DisplayFor(modelItem => item.LockoutEndDateUtc)
</td>
<td>#Html.DisplayFor(modelItem => item.LockoutEnabled)
</td>
<td>#Html.DisplayFor(modelItem => item.AccessFailedCount)
</td>
<td>#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
Your view needs IEnumerable<IdentitySample.Models.ApplicationUser> but you just provide anonymous object by projection ApplicationUser in select new { UserName = u.UserName, Message = u.Message });
The best approach is using different views for different proposes. In each view choose appropriate #model and provide details for that model in your controller method.

Assign editorfor value to radiobutton in mvc view

I have a scenario where i have 3 radio buttons two of them have default values and for the third one I want that it should be assigned the value of a textbox. How can I achieve this below is some of my code :
<tr>
<td>
<label style="padding-bottom:0.5em;font-size:1em">
#Html.RadioButtonFor(model => model.LicenseValidityDuration, "0", new { style = "width:2em" })
Never
</label>
</td>
<td></td>
</tr>
<tr>
<td>
<label style="padding-bottom:0.5em;font-size:1em">
#Html.RadioButtonFor(model => model.LicenseValidityDuration, "-1", new { style = "width:2em" })
Always
</label>
</td>
<td></td>
</tr>
<tr>
<td>
<label style="padding-bottom:0.5em;font-size:1em">
#Html.RadioButtonFor(model => model.LicenseValidityDuration, model => model.LicenseValidityDuration, new { style = "width:2em" })
Days Before Expiry
</label>
</td>
<td>
#Html.EditorFor(model => model.LicenseValidityDuration)
</td>
</tr>

Why do textboxes not clear out after clearing out Model

I have a form which is submitted via ajax to the Controller. The Controller collects the data from the Model and then creates a new ViewModel and passes it to the partial view which is then updated on the Client.
The problem is that the textboxes are not cleared out as expected. The message arrives in the View as expected, so it doesn't make sense that the TextBoxes are not cleared out.
Yet it seems to be a browser issue as this is the resulting HTML, which note, does not have anything in the value:
<input id="Address_Address1" name="Address.Address1" type="text" value="" />
Yet the user sees the value that was priorly entered.
Here is the controller:
//Process Order Here
//This should clear out the ViewModel.
order = new OrderViewModel();
order.Message = "Report Added to your cart";
return PartialView("_NewOrderPartial", order);
This is the partial View:
#model NTC.PropertySearch.Models.OrderViewModel
#using (Ajax.BeginForm("NewOrder", "Order", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "neworder" }))
{
<div id="neworder">
<table>
<tr>
<th style="width: 300px;">
<h3>Enter property address below</h3>
</th>
<th style="width: 30px;"></th>
<th style="width: 300px;">
<h3>Choose your report below</h3>
</th>
</tr>
<tr>
<td>
<div class="form">
<table>
<tr>
<td>
#Html.LabelFor(m => m.Address.Address1)
</td>
<td>
#Html.TextBoxFor(m => m.Address.Address1)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.Address1)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Address.Address2)
</td>
<td>
#Html.TextBoxFor(m => m.Address.Address2)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.Address2)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Address.City)
</td>
<td>
#Html.TextBoxFor(m => m.Address.City)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.City)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Address.State)
</td>
<td>
#Html.TextBoxFor(m => m.Address.State)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.State)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Address.ZipCode)
</td>
<td>
#Html.TextBoxFor(m => m.Address.ZipCode)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.ZipCode)
</td>
</tr>
</table>
<input type="submit" value="Add Report" />
#Html.DisplayFor(m=> m.Message)
</div>
</td>
</tr>
</table>
</div>
The reason for this is because the Html helpers such as TextBox are first looking at the ModelState when binding their values and only after that in the View model. This often happens when people attempt to modify/clear some value to the view model in an HttpPost controller action. The corresponding view will use the initial POSTed value and not the value in the view model.
You should clear the ModelState as well in your controller action:
ModelState.Clear();
order = new OrderViewModel();
Alternatively if you do not want to clear the entire ModelState (although in your case this seems to be the case as you are reinitializing the entire view model) you could clear only some properties that you intend to modify:
ModelState.Remove("SomeProperty");
viewModel.SomeProperty = "some new value";

How to pass a list of objects to a [HTTPPost]controller parameter, in ASP.Net MVC?

i have the next view:
#model IEnumerable<L5ERP.Model.BLL.BusinessObjects.MTR_MonthlyTransfer>
#using (Html.BeginForm("ExpenseMonthlyTransferProcessing", "BudgetTransfer", Model.ToList())){
<table class ="divTable">
<tr>
<th>Transferir</th>
<th>
Clave
</th>
<th>
Monto
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.CheckBoxFor(x => item.MTR_Bool, new { #class = "checkMTR", #checked = "checked" })
</td>
<td>
#Html.TextBoxFor(x => item.MTR_Key, new {#class = "longInput" })
</td>
<td>
#String.Format("{0:F}", item.MTR_Amount)
</td>
</tr>
}
</table>
}
and my controller like this
[HttpPost]
public ActionResult ExpenseMonthlyTransferProcessing(List<MTR_MonthlyTransfer> lstMtr)
{ return View(lstMTR); }
But when i do the post my list is null, how can i send my list through the submit button ?
You should change the #model to an array (L5ERP.Model.BLL.BusinessObjects.MTR_MonthlyTransfer[]) or something else that implements IList<>:
#model L5ERP.Model.BLL.BusinessObjects.MTR_MonthlyTransfer[]
#for (var i = 0; i < Model.Length; i ++) {
<tr>
<td>
#Html.CheckBoxFor(x => Model[i].MTR_Bool, new { #class = "checkMTR", #checked = "checked" })
</td>
<td>
#Html.TextBoxFor(x => Model[i].MTR_Key, new {#class = "longInput" })
</td>
<td>
#String.Format("{0:F}", item.MTR_Amount)
</td>
</tr>
receive a FormCollection and parse the items in it manually
Use F12 to check the post in your navigator to see if it are sending the content you expected.

Resources