MVC - 将整个模型作为参数传递给 javascript 中的 Url.Action
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35219354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC - Pass entire model as parameter to Url.Action in javascript
提问by M0rDoK
Can I pass the entire model as a parameter to Url.Action orsimilar?
我可以将整个模型作为参数传递给 Url.Action 或类似的吗?
Actually, I pass a parameter to the controller and I load the model, but I would like to pass entire model.
实际上,我将参数传递给控制器并加载模型,但我想传递整个模型。
window.location.replace('@Url.Action("Search", "Search", new { idSong = Model.IDSong })');
回答by
Can you. Yes.
你是否可以。是的。
You can pass a simple model containing only properties which are values types or string
using the overload that accepts object
as the 3rd parameter
您可以传递一个简单的模型,该模型仅包含值类型的属性或string
使用接受object
作为第三个参数的重载
@Url.Action("Search", "Search", Model)
Would you want to? No.
你愿意吗?不。
Internally the method will create a Dictionary
based on each properties name and .ToString()
value and convert that to a query string. Not only will the resulting url be ugly, if you have a lot of properties, or the values of the properties contain long strings, you could exceed the query string limit and throw an exception. But the main issue is that any properties which are complex objects or collections will cause binding to fail because, for example, a property which is List<string>
will generate ..?somePropertyName=System.Collections.Generic.List[string]&....
在内部,该方法将Dictionary
根据每个属性名称和.ToString()
值创建一个,并将其转换为查询字符串。不仅生成的 url 会很丑,如果你有很多属性,或者属性的值包含长字符串,你可能会超出查询字符串限制并抛出异常。但主要的问题是,它是复杂的对象或集合任何属性将导致结合失败,因为,例如,它是一个属性List<string>
将产生..?somePropertyName=System.Collections.Generic.List[string]&....
Pass just the model's ID
as your doing now, and get the model again from the repository in your controller.
ID
像现在一样传递模型,然后从控制器的存储库中再次获取模型。
回答by live-love
You can try passing a ViewBag instead:
您可以尝试传递一个 ViewBag:
Url.Action("Search", "Song", new { songId = ViewBag.SongId, songName = ViewBag.SongName})
Controller:
控制器:
[HttpGet]
public PartialViewResult Search(String songId, String songName)
{