pass javascript object ajax beginform mvc - javascript

Hi all I don't know is this possible or not ,that's why guys I need suggestion to achieve this .The thing is I want to post javacript object with ajax-beginform instead of model object to controller . i code like bellow but cant find a way to post the data ,I know jQuery ajax is an option ,but I don't want to use jQuery ajax for posting data in this case .
HTML
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section scripts{
<script type="text/javascript">
var getValues=function()
{
//alert(1)
var v = {
id: $("#txtid").val(), name: $("#txtName").val()
}
console.log(v)
return v;
}
</script>
}
<h2>Index</h2>
#using (Ajax.BeginForm("postvalue", new AjaxOptions { HttpMethod="POST", OnBegin = "getValues" }))
{
<input type="text" id="txtid" />
<br />
<input type="text" id="txtName" />
<br />
<button type="submit" value="Click" style="width:50px;height:50px">Click</button>
}
Contoller
namespace AjaxBeginForm.Controllers
{
public class AjaxBeginFormController : Controller
{
// GET: AjaxBeginForm
public ActionResult Index()
{
return View();
}
public void postvalue(searchValues objsearchValues)
{
}
}
public class searchValues
{
public Int64 id { get; set; }
public string name { get; set; }
}
}
I want to post data to controller and catch them in objsearchValues .

Put the JS value in a hidden field in the form and when the form is submitted it will pass the value back to the controller.

Related

Trying to post a list collection to the controller with ajax

I'm trying to post a list collection to the controller with a full page post back to the server. The data from the client side is written with JavaScript / jQuery and the server code is written in C# using ASP.Net MVC.
I'm not sure what the issue is because when the ItemCheck method is hit with a breakpoint on the first curly brace after the method name but the model object Items property is null even though it's in the form data mentioned further below.
The code below is simplified for ease and is not working.
Input hidden field in the view where the JavaScript adds an item to it each time add button is pressed.
#model UI.ViewModels.ItemResource
#Html.HiddenFor(model => model.Items, new { #id = "Items" })
<button class="btn-default btn" id="AddItem" name="AddItem" type="button" disabled>Add</button>
JavaScript
var items = [];
// This code only adds an item to the items collection input hidden
// field for a full page post back to the server.
var addItemToList = function () {
var item = {
ItemDate: $(date).val(),
ItemAmount: $(amount).val()
};
items.push(item);
$("#Items").val( JSON.stringify(items));
};
Controller
public ActionResult ItemCheck(ItemViewModel model)
{
if (result.IsValid)
{
model.Items = _anotherViewModel.Items;
_anotherViewModel.Items= null;
model.IsValid = _itemService.Save(model, _Itemhelper.GetUserId());
}
else
{
//Validation here
}
return View(model);
}
ViewModels
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace UI.ViewModels.ItemResource
{
public class ItemsViewModel
{
public ItemsViewModel()
{
Items = new List<ItemViewModel>();
}
[JsonBindable]
public List<ItemViewModel> Items { get; set; }
}
public class ItemViewModel
{
public DateTime ItemDate { get; set; }
public decimal ItemAmount { get; set; }
}
}
FormData
Items: [{"ItemDate":"2020-06-05","ItemAmount":"2267"}]

Using C# MVC multiple dynamic models in View

I have a View with several form that I'm using for searching and displaying the results as partial View in like SearchByNumber, SearchByVehicle, etc.
I'm trying to load view and execute search for different forms by posting link with querystring like www.example.com/Search?number=101010 from different view.
For the first form, SearchByNumber I only have one parameter, string number and i'm returning view with dynamic Model and its working like it should, but I only manage to make search for this form.
Here is my controller:
public ActionResult Index(string number)
{
return View(model: number);
}
and in the View I have:
<form id="searchbynumberform">
Search By Any Number:
<div class="input-group input-group-sm">
<input type="text" class="form-control" name="number" id="number" value="#Model">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" name="numbersearch" id="numbersearch" disabled>
Search
</button>
</span>
</div>
</form>
My Question is, if anyone can help me, How to perform search let's say on the second form where I have int type and string name parameters?
Thank You in advance...
At the moment your Model is only the search string that was entered, which seems rather incomplete. It would make a lot more sense if the Model also contained the actual search results, which after all is what the user wants to see. And then you can also add the other search properties.
The MVC approach for this is to create a (View)Model class, somewhere in your project, something like this:
public class SearchModel
{
public string Number { get; set; }
public int? Type { get; set; }
public string Name { get; set; }
public List<SearchResult> SearchResults { get; set; }
}
And then use it e.g. like this:
public ActionResult Index(string number)
{
var model = new SearchModel
{
Number = number,
SearchResults = GetByNumber(number)
};
return View(model);
}
public ActionResult IndexOther(int type, int name)
{
var model = new SearchModel
{
Type = type,
Name = name,
SearchResults = GetByTypeAndName(type, name)
};
return View(model);
}
And in your Index.cshtml:
#model SearchModel
#* You can now use Model.Number, Model.Type, Model.Name and Model.SearchResults. *#

Use javascript variable in c#

Is it possible to use js variables in c# code?
This is my model:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual ICollection<Department> Parent { get; set; }
}
And this is my cshtml:
#model List<inspinia.models.Department>
<select name="DepartmentId" class="form-control" id="Department">
#foreach (var item in Model)
{
<option value="#item.Id">#item.Name</option>
}
</select>
<script>
$(document).ready(function () {
$("#Department").on("change", function () {
var DepartmentId = $('option:selected', this).attr('value');
//the problem in the next line.
#foreach(var item in Model.Where(x=>x.ParentId==#:DepartmentId))
{
#:alert(#item.id)
}
});
});
</script>
Well I am having error when I use
Model.Where(x=>x.ParentId==#:JAVASCRIPT VARIABLE).
Is there any way to do it or I definitely have to use ajax ?
No you can't, because the javascript code's is for clientside and razor in serverside.
You have two solutions:
1- Put all departement in list(<ul>) and use JQuery for get your data on change
2- Use jquery ajax and get data directly from controller(create controller for that)

Set path of selected file to model in view

I am trying to set the full path of the selected file into the model in the view.
Controller FileController:
public async Task<IActionResult> Create(CreateFileViewModel model)
{
if (ModelState.IsValid)
{
var file = new File
{
Path = model.Path
};
_context.Add(file);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(model);
}
Model CreateFileViewModel:
public class CreateFileViewModel
{
public string Path { get; set; }
}
Model File:
public class File
{
public int Id { get; set; }
public string Path { get; set; }
}
ViewForm Create:
<form asp-action="Create">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Path" class="control-label"></label>
<input asp-for="Path" id="selectedFile" type="file" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
Script in Create:
<script>
document.getElementById('selectedFile').onmouseout = function () {
#Model.Path=this.value;
};
</script>
But
#Model.Path=this.value;
this not working. Ofc I cannot convert between razor and javascript variables. But I don't know another way how to set full path of selected file into the model variable.
This
<input asp-for="Path" id="selectedFile" type="file" />
set into model variable just file name, without a path.
#Model.Path is server side i.e. c# code, while this.value is java script code which is client side code, so the server side code will get executed when view is rendered while your js code with execute on particular event in your html.
What you need is to update the hidden value via javascript and it will post back in controller with updated value and will also work in html with the updated value.
Your hidden field will be rendered with id Path, so you can write :
document.GetElementById("Model").value = this.value;
or if you have jquery library included in your application, then you can make use of that as well:
$("#Path").val(this.value);
This way when the model will get posted back to controller, the Path property will have the updated value which would be the path you have assigned via js code.
Hope it helps!

Bind multiple files to array with properties

I have a basic HTML form with <input type="file" multiple> inside. For each chosen file I create a description.
Now I want to bind them to PostedPhotoViewModel[] PostedPhotos;:
public abstract class PostedPhotoViewModel
{
public string Description { get; set; }
public HttpPostedFileBase File { get; set; }
}
I don't know how to prepare my input to do such a thing. Is it possible? Or do I have to do some tricks to achieve my target?
#Html.TextBoxFor(m => m.PostedPhotos, new { #name = "PostedPhotos", type = "file", multiple="multiple" })
I tried to force it in such a way, but didn't work:
myForm.submit(function(e) {
myInput.files = $.map(myInput.files, function(element) {
return {File: element, Description: "Test description"}
});
return true;
});
It's basic ASP.NET MVC 5 project.
I would replace this:
#Html.TextBoxFor(m => m.PostedPhotos, new { #name = "PostedPhotos", type = "file", multiple="multiple" })
With just:
<input type="file" name="files" multiple="multiple" />
Then in the controller do something like:
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
I think the nested view model list binding with a textbox property is making it far more complicated than it is.

Categories