Using buttons instead of a text box to pass data asp.net mvc3 - asp.net-mvc-3

hi I'm creating a project where the user all the user are running off the same instance using the singleton design pattern. when user types a value into a textbox. It will then wait until everyone else has type a value and then display the results. My question is can this be done using buttons that send a value to the model instead of a textbox. e.g. multiple buttons each one sending a different value.
Heres my code now.
view
#{
ViewBag.Title = "Voting";
}
#using (Html.BeginForm())
{
<fieldset>
<div class="editor-label">
What is you vote?
</div>
<div class="editor-field">
#Html.TextBox("Vote")
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
controller
public ActionResult PlanVote()
{
return View();
}
[HttpPost]
public ActionResult PlanVote(int vote)
{
PlanModel myModel = PlanModel.Instance;
myModel.Vote(vote);
if (PlanModel.Instance.currentstate == PlanState.displaying)
{
return RedirectToAction("Index", "Plan");
}
else
{
return RedirectToAction("Waiting", "Plan");
}
}
model
public void Vote(int Votes)
{
countVotes++;
ivote.Add(Votes);
if (countVotes >= iCount)
{
currentstate = PlanState.displaying;
}
}
I'm still Quite new to MVC and would be great-full for any help thanks

Just remove stand alone submit button and use one submit per vote
#using (Html.BeginForm())
{
<fieldset>
<div class="editor-label">
What is you vote?
</div>
<div class="editor-field">
<input type="submit" name="vote" value="1" />
<input type="submit" name="vote" value="2" />
<input type="submit" name="vote" value="3" />
</div>
</fieldset>
}

Related

How can I get full info on update page

I have an ASP.NET Core MVC project without Entity Framework.
When I click on the "update" button, I want to update page and make it does not become empty.
This is my view:
<div class="form-group">
<form asp-action="OdemeTurGuncelle">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
ID
<input asp-for="odemetur_id" class="form-control" />
<span asp-validation-for="odemetur_id" class="text-danger"></span>
</div>
<div class="form-group">
Ödeme Türü
<input asp-for="odemetur_adi" class="form-control" />
<span asp-validation-for="odemetur_adi" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
And my controller :
[HttpGet]
public IActionResult OdemeTurGuncelle()
{
return View();
}
[HttpPost]
public IActionResult OdemeTurGuncelle(OdemeTur odemeTur)
{
string constr = Genel.conString;
using (NpgsqlConnection con = new NpgsqlConnection(constr))
{
string query = "UPDATE odemeturleri SET odemetur_adi=#odemetur_adi WHERE odemetur_id=#odemetur_id";
using (NpgsqlCommand cmd = new NpgsqlCommand(query))
{
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#odemetur_id", odemeTur.odemetur_id);
cmd.Parameters.AddWithValue("#odemetur_adi", odemeTur.odemetur_adi);
cmd.ExecuteNonQuery();
con.Close();
}
}
// return View(ders);
return RedirectToAction("Index");
}
I can do it with Entity Framework, but I want to do it without EF

ApplicationDbContext.Update() doesn't update but saves it as a new record

I am playing in the new APS.NET 5 RC1 environment but the default edit action creates a new entity of the object. I am searched the whole day finding where it goes wrong but I can't find out why it goes wrong.
Controller:
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using SSTv5.Models;
using SSTv5.Models.Organisations;
using SSTv5.Models.Views;
using System.Collections.Generic;
using SSTv5.Models.Global;
namespace SSTv5.Controllers
{
public class OrganisationTypesController : Controller
{
private ApplicationDbContext _context;
private List<Breadcrumb> _bcList = new List<Breadcrumb>();
public OrganisationTypesController(ApplicationDbContext context)
{
_context = context;
}
#region Edit
// GET: OrganisationTypes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
_bcList.Add(new Breadcrumb("OrganisationTypes", true, "Index", "Index"));
_bcList.Add(new Breadcrumb("Edit", false));
ViewBag.BcList = _bcList;
if (id == null)
{
return HttpNotFound();
}
OrganisationType organisationType = await _context.OrganisationType.SingleAsync(m => m.OrganisationTypeId == id);
if (organisationType == null)
{
return HttpNotFound();
}
return View(organisationType);
}
// POST: OrganisationTypes/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(OrganisationType organisationType)
{
if (ModelState.IsValid)
{
_context.Update(organisationType);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(organisationType);
}
#endregion
}
}
Form:
#model SSTv5.Models.Organisations.OrganisationType
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
<form asp-action="Edit">
<div class="form-horizontal">
<h4>OrganisationType</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrganisationTypeName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="OrganisationTypeName" class="form-control" />
<span asp-validation-for="OrganisationTypeName" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="ClassIcon" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ClassIcon" id="classIcon" />
<span asp-validation-for="ClassIcon" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Edit" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}
For anyone else who has this problem the answer is quite simple.
The form doesn't send the ID of the object with it. The only thing you need to do is put the id in a hidden field in the form. Then it will work fine.

MVC 5 HTML helper for client side validation for value not in model

I'm following the MVC tutorial here to add a search/filter textbox:
http://www.asp.net/mvc/overview/getting-started/introduction/adding-search
I've added the filter textbox to my page:
#using (Html.BeginForm()) {
<p> Title: #Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" /></p>
}
How do I perform client side validation on the textbox to ensure something was entered?
When you automatically created the controller and views based on a model, it creates this handy HTML helper:
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
Can something similar be used for a value not in your model or do you have to add custom jquery/html?
Edit:
Thanks for the direction everyone. Just adding some more information now. I've created a new class in my existing model:
public class SearchItem
{
[Required]
[StringLength(100, MinimumLength = 5, ErrorMessage = "This is my test error message")]
public string SearchString { get; set; }
}
Then inside the controller, I've created a partial view:
[ChildActionOnly]
[AllowAnonymous]
public PartialViewResult Search()
{
return PartialView();
}
Then I've created a new Search.cshtml with:
#model App.Models.SearchItem
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<h4>#Html.LabelFor(model => model.SearchString, "Search:", htmlAttributes: new { #class = "control-label col-md-2" })</h4>
<div class="col-md-10 input-max-width">
#Html.EditorFor(model => model.SearchString, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SearchString, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="submit" value="Search" class="btn btn-primary" />
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Then on my existing page, I add it with this:
#Html.Action("Search", "Items")
When I enter no text into the textbox and click the Search button, the page just refreshes and I get no client side validation.
My HTML looks like this:
<form action="/Items/Index" method="post"> <div class="form-group">
<h4><label class="control-label col-md-2" for="SearchString">Search:</label></h4>
<div class="col-md-10 input-max-width">
<input class="form-control text-box single-line" data-val="true" data-val-length="This is my test error message" data-val-length-max="100" data-val-length-min="5" data-val-required="The SearchString field is required." id="SearchString" name="SearchString" type="text" value="" />
<span class="field-validation-valid text-danger" data-valmsg-for="SearchString" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Search" class="btn btn-primary" />
</div>

Ajax GET request calling POST instead (ASP.NET MVC5)

I've created an ajax GET call to perform a search feature. But every time the search button is clicked, it is calling the POST instead (thereby returning null error for the model). I am not sure what I have done wrong. Care to give a hand please?
My controller:
//
// GET: /DataEntry/ChargeBack
public ActionResult ChargeBack(string dwName, string searchTerm = null)
{
var model = createModel();
if (Request.IsAjaxRequest())
{
return PartialView("_Suppliers", model);
}
return View(model);
}
//
// POST: /DataEntry/ChargeBack
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChargeBack(ChargeBackViewModel model)
{
if (ModelState.IsValid)
{
model.someAction();
}
return View(model);
}
My Main View:
#model CorporateM10.Models.ChargeBackViewModel
#using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SuppliersList"
}))
{
#Html.AntiForgeryToken()
<input type="search" name="searchTerm" class="form-control col-md-2" />
<input type="submit" value="Search by Name" class="btn btn-info" />
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.Partial("_Suppliers", Model)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
My Partial View:
#model CorporateM10.Models.ChargeBackViewModel
<div class="form-group" id="SuppliersList">
<div class="col-md-10">
#Html.EditorFor(model => model.Suppliers)
#Html.ValidationMessageFor(model => model.Suppliers)
</div>
</div>
I've found it. It is being caused by not including jquery.unobtrusive-ajax library. Once included, the Ajax action works as intended.

View values not returned to the controller action

Can anyone tell whats wrong with my view? my model values is displayed correctly in my view but it is not returned to the controller action. public ActionResult DeleteConfirmed(ClientModel contacts) my ClientModel is returned null.
View:
#model ContactManager.Models.ClientModel
#{
ViewBag.Title = "Delete Information";
}
<h2>Delete Information</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Details</legend>
<div class="display-label">ID</div>
<div class="display-field">
#Html.DisplayFor(model => model.CanaClie0012.Client00130012)
</div>
<div class="display-label">Name</div>
<div class="display-field">
#Html.DisplayFor(model => model.Clientes0013.Nombre0013)
</div>
<div class="display-label">Contact Number</div>
<div class="display-field">
#Html.DisplayFor(model => model.CanaClie0012.Direcc0012)
</div>
<div class="display-label">Country</div>
<div class="display-field">
#Html.DisplayFor(model => model.CanaClie0012.F1Pais00200012)
</div>
</fieldset>
#using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
#Html.ActionLink("Back to List", "Index")
</p>
}
Controller Action:
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(ClientModel contacts)
{
contacts.Clientes0013.Client0013 = contacts.CanaClie0012.Client00130012;
contacts.Clientes0013.F1Pais00200013 = contacts.CanaClie0012.F1Pais00200012;
Clientes0013 clientes0013 = db.Clientes0013.Find(contacts.Clientes0013.Client0013, contacts.Clientes0013.F1Pais00200013);
db.Clientes0013.Remove(clientes0013);
db.SaveChanges();
return RedirectToAction("Index");
}
1. Keep the helpers inside the Form like below.
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, null))
{
#Html.DisplayFor(i => i.PropertyName);
<input type="submit" name="Submit" value="Submit" />
}
2. In order to Submit the form and send the model in Post Action Method, you have to use a Hidden Field along with each DisplayFor Helper.
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, null))
{
#Html.HiddenFor(i => i.PropertyName);
#Html.DisplayFor(i => i.PropertyName);
<input type="submit" name="Submit" value="Submit" />
}
3. You will not be able to see the Model values in Post Action Method when the View is like below..
#Html.HiddenFor(i => i.PropertyName);
#Html.DisplayFor(i => i.PropertyName);
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, null))
{
<input type="submit" name="Submit" value="Submit" />
}
This is because you are using DisplayFor for all your properties. DisplayFor will not send anything in a POST, it doesn't create an input.
You could add #Html.HiddenFor(model => model.CanaClie0012.Client00130012) , etc. to each one of your properties in order for your view to send anything back.

Resources