how can i assign value to textbox in MVC - Sharepoint Provider-hosted - asp.net-mvc

I want to get and assign value to my textbox from controller.
here is my textbox:
<input type="text" class="form-control" id="RegardingTo" name="RegardingTo" value="??????"/>
then i want to get the value from this action.
public ActionResult Edit(int? RequestID)
{
if (RequestID <= 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var ReqID = db.usp_RequestGetDetails(RequestID);
if (ReqID == null)
{
return HttpNotFound();
}
return View();
}
please help :)

Yes you can assign value to the textbox using Model, First of all create a model then link that model with your view. And In Controller assign the value to model and return to the view.
Or At runtime if you want to assign the value to your text box then you can use Ajax call to your controller and get the value.
Please revert in case of any query.

See what i am doing to do the same, Make a custom model with your relevant fields, then assign values to them in controller, and pass this values to View, And that's it. :)
Custom Model
public partial class QuoteParameter
{
public Nullable<System.DateTime> TripStartDateLimit { get; set; }
public Nullable<System.DateTime> TripEndDateLimit { get; set; }
public int PolicyId { get; set; }
}
Controller
public ActionResult Index()
{
QuoteParameter quote = new QuoteParameter();
quote.TripEndDateLimit = DateTime.Now;
quote.TripEndDateLimit = DateTime.Now;
quote.PolicyId = 5;
return View(quote);
}
View
#model EHIC.Models.Models.QuoteParameter
By Razor syntax
<div class="row-fluid span12">
<div class="span4">
<p><strong>Trip Start Date Limit :</strong></p>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.TripStartDateLimit, "{0:dd/MM/yyyy}", new { #class = "form-control", #placeholder = "Policy StartDate Limit", #required = true })
</div>
</div>
<div class="row-fluid span12">
<div class="span4">
<p><strong>Trip End Date Limit :</strong></p>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.TripEndDateLimit, "{0:dd/MM/yyyy}", new { #class = "form-control", #placeholder = "Policy EndDate Limit", #required = true })
</div>
</div>
By HTML Code
<input type="text" class="form-control" id="TripStartDateLimit" name="TripStartDateLimit" value="#Model.TripStartDateLimit"/>
<input type="text" class="form-control" id="TripEndDateLimit" name="TripEndDateLimit" value="#Model.TripEndDateLimit"/>
EDIT
By Click on this button you can send the PolicyId(as an example) to controller, and then you can do whatever you want there..!!!
<a href='../../controller/Edit?PolicyId=#Models.PolicyId'>
<span title='Edit'></span>
</a>
#Html.ActionLink("Edit","Edit", new { id = item.RequestID })
You can find the PolicyId which you sent from the Edit Page..
public ActionResult Edit(int id)
{
//Get your data from Store_procedure..
return View();
}

Related

ASP.NET MVC Select Drop Down list, set the default value and retrieve the selected value

The answer I am sure is simple. I have a <select> with a list of values. For edit mode, I want the drop down to show the current value and have the selected when the view renders. And also when the form is submitted take a possible new selected value and pass it back to the controller. Any help would be greatly appreciated.
From the view:
<td style="padding:15px">
<label asp-for="OrganizationTypeId" class="form-control-label" style="font-weight:bold">Organization</label>
<select asp-for="OrganizationTypeId" class="form-control" style="width:450px" asp-items="#(new SelectList(Model.orgTypes, "Id", "OrganizationName"))">
<option value="" disabled hidden selected>Select Organization....</option>
</select>
</td>
Code in the controller:
dr = _electedOfficials.getDeputyReg(jurisdictionId, Id);
dr.orgTypes = _electedOfficials.GetOrganizationTypes(jurisdictionId);
return View(dr);
OrgTypes class
public int Id { get; set; }
public string OrganizationName { get; set; }
One of the solutions is preparing list of the SelectListItem and return the selected item Id to the controller:
public ActionResult Index()
{
// ...
dr.orgTypes = _electedOfficials.GetOrganizationTypes(jurisdictionId);
var model = dr.orgTypes.Select(d => new SelectListItem() { Selected = (d.Id == /* id of default selection*/), Text = d.OrganizationName, Value = d.Id.ToString() }).ToList();
return View(model);
}
[HttpPost]
public ActionResult Index(int? seletedId)
{
if (ModelState.IsValid && seletedId.HasValue)
{
// Processing the selected value...
}
return RedirectToAction("Index");
}
In the view:
#model IEnumerable<SelectListItem>
<script type="text/javascript">
$(document).ready(function () {
var e = document.getElementById("OrgTypesList");
$("#SeletedId").val(e.options[e.selectedIndex].value);
});
function changefunc(val) {
$("#SeletedId").val($("#OrgTypesList").val());
}
</script>
#using (Html.BeginForm("Index", "Home"))
{
#* To pass `SeletedId` to controller *#
<input id="SeletedId" name="SeletedId" type="hidden" />
<label asp-for="OrganizationTypeId" class="form-control-label" style="font-weight:bold">Organization</label>
#Html.DropDownList("OrgTypesList", Model, "Select Organization...", new { #class = "form-control", #onchange = "changefunc(this.value)" })
<button type="submit" class="btn btn-primary">Save</button>
}

Razor pages, detect text changes in textview

I have a razor page where the user can make some options from a dropdownlist and than enter some value.
See attached image
What i want to achieve is that as user change any of the textboxes, call the appropriate handler function.
So as soon user enter some value in the textfield 1, the one to the right of textlabel "Some value" i want to do some calculation and update the textfield 2, the one to the right of textlabel "Some other value" . And vice versa for the other textfield.
I have following code
#page
#model CurrencyConverter.Pages.ConvertModel
#{
ViewData["Title"] = "Convert";
}
<div>
#if (!string.IsNullOrEmpty(Model.ResultInfo))
{
<p>#Model.ResultInfo</p>
}
</div>
<form method="post">
<div>
#Html.DropDownListFor(m => m.CurencyModel.FirstCurrency, new SelectList(Model.Options, "Value", "Text"), "Select currency", new { #class = "css-class" })
<input asp-for="CurencyModel.TotalAmountFirstCurrency" />
</div>
<div>
#Html.DropDownListFor(m => m.CurencyModel.SecondCurrency, new SelectList(Model.Options, "Value", "Text"), "Select currency", new { #class = "css-class" })
<input asp-for="CurencyModel.TotalAmounSecondCurrency" />
</div>
<div>
<button type="submit" asp-page-handler="FirstCurrency">Submit first currency</button>
<button type="submit" asp-page-handler="SecondCurrency">Submit second currency</button>
</div>
</form>
the cshtml.cs file looks like this
public class ConvertModel : PageModel
{
[TempData]
public string ResultInfo { get; set; }
[BindProperty]
public CurrencyModel CurencyModel { get; set; }
[BindProperty]
public IEnumerable<SelectListItem> Options
{
get; set;
}
public ConvertModel()
{
//initalization
}
public async Task<IActionResult> OnPostFirstCurrency()
{
if(!ModelState.IsValid)
{
return Page();
}
//given first currency calculate the second from the first using some formula
}
public async Task<IActionResult> OnPostSecondCurency()
{
if (!ModelState.IsValid)
{
return Page();
}
//given second currency calculate the second from the first using some formula
}
}
what i want to achieve is in
<div>
#Html.DropDownListFor(m => m.CurencyModel.SecondCurrency, new SelectList(Model.Options, "Value", "Text"), "Select currency", new { #class = "css-class" })
<input asp-for="CurencyModel.TotalAmounSecondCurrency" onchanged=asp-page-handler="FirstCurrency"/>
But this seems not possible with only pure razor and c# syntax.

How to pass different list of data from view to controller MVC

currently I facing a very tricky problem of passing different list of data from view to controller.
I have created two input box to submit my data to controller so that it can be saved into CreateAccountsDB and further display it in the list of
Selected Subcon when Create button is pressed.
The problem I face here is:
when pressing the Create button with entered data from NewCompanyName textbox and NewEmail textbox, those entered data do pass data from View to Controller and save data into CreateAccountDB (not showing in View), but the entered data is not displaying in the list of Selected Subcon.
Create View
Here is the model.
public class Tender
{
public int ID { get; set; }
public string CompanyName { get; set; }
public List<CreateAccount> FrequentCompanyName { get; set; }
public List<CreateAccount> SuggestCompanyName { get; set; }
public List<CreateAccount> SelectedCompanyName { get; set; }
public string CompanyNameNew { get; set; }
public string EmailNew { get; set; }
public int? TradeID { get; set; }
public virtual Trade Trade { get; set; }
public int? CreateAccountID { get; set; }
public virtual CreateAccount CreateAccount { get; set; }
}
Here is the Get Method of Create function in controller:
[httpGet]
public ActionResult Create(int? id)
{
Tender tender = new Tender();
tender.FrequentCompanyName = db.createaccountDB.Include(tm => tm.Trade).Where(td => td.Frequency == 32).ToList();
tender.SuggestCompanyName = db.createaccountDB.Include(tm => tm.Trade).ToList();
if (tender.SelectedCompanyName == null)
{
tender.SelectedCompanyName = new List<CreateAccount>().ToList();
}
return View(tender);
}
and Here is my Post Method of Create function:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,CompanyName,TradeID,FrequentCompanyName,SelectedCompanyName,CreateAccountID")] Tender tender ,string CompanyNameNew, string Emailnew)
{
CreateAccount accnew = new CreateAccount();
accnew.CompanyName = CompanyNameNew;
accnew.Email = Emailnew;
if(ModelState.IsValid)
{
db.createaccountDB.Add(accnew);
db.SaveChanges();
}
if (tender.SelectedCompanyName == null)
{
tender.SelectedCompanyName = new List<CreateAccount>().ToList();
}
tender.FrequentCompanyName = db.createaccountDB.Include(tm => tm.Trade).Where(td => td.Frequency == 32).ToList();
tender.SuggestCompanyName = db.createaccountDB.Include(tm => tm.Trade).ToList();
tender.SelectedCompanyName.ToList().Add(accnew);
return View(tender);
}
and Here is my Create View:
#model Tandelion0.Models.Tender
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group">
#*#Html.LabelFor(model => model.ProjectName, htmlAttributes: new { #class = "control-label col-md-3" })*#
<div class="col-md-3">
<h5>New Company Name</h5>
#Html.EditorFor(model => model.CompanyNameNew, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CompanyNameNew, "", new { #class = "text-danger" })
</div>
<div class="col-md-3">
<h5>New Email</h5>
#Html.EditorFor(model => model.EmailNew, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailNew, "", new { #class = "text-danger" })
</div>
<div class="container" align="center">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
<div class="container row">
<!--selected subcon column-->
<div class="container row col-sm-4">
<h4>
Selected Subcon
</h4>
<div style="overflow-y: scroll; height:250px;">
<table class="table table-hover">
#foreach (var item in Model.SelectedCompanyName)
{
<tbody>
<tr>
<td>
#Html.DisplayFor(modelItem => item.CompanyName)
</td>
</tr>
</tbody>
}
</table>
</div>
</div>
</div>
}
So far I manage to save data from view into CreateAccountsDB when create button is pressed, but those data just couldn't pass it from Post method Create function to Get method Create function in Controller. The data and the list become null immediate after come out from post method Create function.
Because of data becomes null, the view couldn't receive any data from controller.
May I know how can i solve the the problem of passing data from controller to view? Is the way I pass data totally wrong?
Any advice is truly appreciated.
In your HttpPost Action method :
Instead of :
tender.SelectedCompanyName.ToList().Add(accnew);
You should be doing:
tender.SelectedCompanyName.Add(accnew);
Calling ToList().Add(object) won't actually add to SelectedCompanyName.Instead it will add to the new list object created by calling ToList() method which you are not assigning back to tender.SelectedCompanyName.
A better approach however would be to use Post/Redirect/Get Pattern.
Instead of returning a view from your post method , do a temorary redirect to your [HttpGet]Create action method passing the id of the tender.

Data annotation trigger validation on Get method

I have this viewmodel
public class ProductViewModel : BaseViewModel
{
public ProductViewModel()
{
Categories = new List<Categorie>
}
[Required(ErrorMessage = "*")]
public int Code{ get; set; }
[Required(ErrorMessage = "*")]
public string Description{ get; set; }
[Required(ErrorMessage = "*")]
public int CategorieId { get; set; }
public List<Categorie> Categories
}
My controller like this
[HttpGet]
public ActionResult Create(ProductViewModel model)
{
model.Categories = //method to populate the list
return View(model);
}
The problem is, as soon as the view is exhibited, the validation is fired.
Why this is happening?
Thanks in advance for any help.
Update
The view is like this
#using (Html.BeginForm("Create", "Product", FormMethod.Post, new { #class = "form-horizontal", #role = "form" }))
{
<div class="form-group">
<label for="Code" class="col-sm-2 control-label">Code*</label>
<div class="col-sm-2">
#Html.TextBoxFor(x => x.Code, new { #class = "form-control"})
</div>
</div>
<div class="form-group">
<label for="Description" class="col-sm-2 control-label">Desc*</label>
<div class="col-sm-2">
#Html.TextBoxFor(x => x.Description, new { #class = "form-control", maxlength = "50" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Categorie*</label>
<div class="col-sm-4">
#Html.DropDownListFor(x => x.CategorieId, Model.Categories, "Choose...", new { #class = "form-control" })
</div>
</div>
You GET method has a parameter for your model, which means that the DefaultModelBinder initializes and instance of the model and sets its properties based on the route values. Since your not passing any values, all the property values are null because they all have the [Required] attribute, validation fails and ModelState errors are added which is why the errors are displayed when the view is first rendered.
You should not use a model as the parameter in a GET method. Apart from the ugly query string it creates, binding will fail for all properties which are complex objects and collections (look at you query string - it includes &Categories=System.Collections.Generic.List<Categorie> which of course fails and property Categories will be the default empty collection). In addition, you could easily exceed the query string limit and throw an exception.
If you need to pass values to the GET method, for example a value for Code, then you method should be
[HttpGet]
public ActionResult Create(int code)
{
ProductViewModel model = new ProductViewModel
{
Code = code,
Categories = //method to populate the list
};
return View(model);
}

mvc getting and sending data from dropdown and datetimepicker

hello everyone I have a question. I have a form which consist of dropdown textbox and datetimepicker. I can fill my dropdown from my model but I cannot post the data to the database. Here are my codes
My Controller codes this is where the data selected and shown in view
public ActionResult orderProduct()
{
Repository<OrderProduct> _ro = new Repository<OrderProduct>();
IEnumerable<OrderProduct> _orderProduct = _ro.All().OrderByDescending(o => o.id);
return View(_orderProduct);
}
I am filling the dropdownlist from database
public ActionResult addOrderProduct()
{
/*
Repository<Workshop> _rw = new Repository<Workshop>();
IEnumerable<Workshop> _workshop = _rw.All().OrderByDescending(o => o.id);
IEnumerable<SelectListItem> _selectList = from w in _workshop
select new SelectListItem {
Text = w.name,
Value = w.id.ToString()
};
*/
Repository<Workshop> _rw = new Repository<Workshop>();
IEnumerable<SelectListItem> _workshopSelectListItem = _rw.All().AsEnumerable().Select(s =>
new SelectListItem {
Text = s.name, Value=s.id.ToString()
});
ViewData["dropdown"] = _workshopSelectListItem;
return View();
}
here I am trying to post my data to the database. I cannot select data from dropdown and datetimepicker also I cannot post this data by writing manually.
public ActionResult orderProductAdd(int adet, float cmt)
{
Repository<OrderProduct> _rp = new Repository<OrderProduct>();
OrderProduct _orderProduct = new OrderProduct { workshopId = 1, orderId = 1, value = adet, shipDate = new DateTime(2005, 02, 01), cmt = cmt };
return RedirectToAction("orderProduct");
}
this is my model
[Table("OrderProduct")]
public class OrderProduct
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public int orderId { get; set; }
[ForeignKey("orderId")]
public virtual Order order { get; set; }
public int workshopId { get; set; }
[ForeignKey("workshopId")]
public virtual Workshop workshop { get; set; }
public int value { get; set; }
public float cmt { get; set; }
public DateTime shipDate { get; set; }
/*
[id]
,[orderId]
,[workshopId]
,[value]
,[cmt]
,[shipDate]
*/
}
and also this is my view "addOrderProduct"
<form action="/Order/orderProductAdd" class="form-horizontal">
<div class="control-group">
<label class="control-label">Atölye Seçiniz</label>
<div class="controls">
#Html.DropDownList("dropdown",(IEnumerable<SelectListItem>)ViewData["dropdown"],"secim yapınız", new { #class = "span6 chosen" })
#*<select class="span6 chosen" data-placeholder="Choose a Category" tabindex="1">
<option value=""></option>
<option value="Category 1">A1</option>
<option value="Category 2">A2</option>
<option value="Category 3">A3</option>
<option value="Category 4">A4</option>
</select>*#
</div>
</div>
<div class="control-group">
<label class="control-label">Adet Giriniz</label>
<div class="controls">
<input type="text" class="span6 " name="adet" />
<span class="help-inline">Sadece sayı giriniz</span>
</div>
</div>
<div class="control-group last">
<label class="control-label">İhracat Tarihi</label>
<div class="controls">
<div id="ui_date_picker_inline"></div>
</div>
</div>
<div class="control-group">
<label class="control-label">Cmt</label>
<div class="controls">
<input type="text" class="span6 " name="cmt" />
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Onayla</button>
#*<button type="button" class="btn">Cancel</button>*#
</div>
</form>
How can I solve this ? Thank you.
The first argument in the DDL (below) is the assigned parameter being passed back to the server. When you call the action you're not passing the parameter dropdown. You're only calling int adet, float cmt but not a parameter called dropdown
#Html.DropDownList("dropdown",(IEnumerable<SelectListItem>)ViewData["dropdown"],
"secim yapınız", new { #class = "span6 chosen" })
So update your code to something like the one below:
public ActionResult orderProductAdd(int adet, float cmt, string dropdown){
// DO SOMETHING HERE
}
I can't see the input control which is being constructed for the DATETIME part of your query, however it will be similar to the above. Ensure the name of the INPUT matches the parameters being passed back to the server.

Resources